Create a discord bot that notifies unilaterally with python (use only requests and json)

Contents

When it comes to making a discord bot using python, it seems that there are roughly two types.

--Types that work interactively ――It seems that a library called discord.py is convenient. Not covered in this article. --One-sided notification type ――Click here to notify regularly. This is explained below.

webhook URL acquisition

You need to get it for each channel. You can refer to "Get Webhook URL" on this page. Option settings can be made with code, so you can pass it.

-[Ruby] Post a message to Discord with a webhook

Abridged edition

The simplest configuration is as follows.

import requests, json


webhook_url  = 'Webhook URL you just got'
main_content = {'content': 'Text to send'}
headers      = {'Content-Type': 'application/json'}

response     = requests.post(webhook_url, json.dumps(main_content), headers=headers)

Successful transmission! SS 2020-07-12 21.04.33.png

The look of the bot

The look of the bot can be defined in the code as follows: It seems that the URL of the image is required to set the icon. Below, the URL of the twitter account icon is given. In the case of a local image file, is there no choice but to set it when getting the Webhook URL?

import requests, json


webhook_url  = 'Webhook URL you just got'
main_content = {
                   'username': 'name',
                   'avatar_url': 'Image URL',
                   'content': 'text'
               }
headers      = {'Content-Type': 'application/json'}

response     = requests.post(webhook_url, json.dumps(main_content), headers=headers)

Successful transmission! SS 2020-07-12 21.07.59.png

I want to elaborate the appearance of the message

Use embeds. For more information, click here (https://birdie0.github.io/discord-webhooks-guide/structure/embeds.html). An example is given below.

import requests, json


webhook_url  = 'Webhook URL you just got'
embeds       = [
                   {
                       'description': 'google page',
                       'color': 15146762,
                       'image': {
                           'url': 'Image URL'
                       }
                    }
               ]
main_content = {
                   'username': 'name',
                   'avatar_url': 'Image URL',
                   'content': 'text',
                   'embeds': embeds
               }
headers      = {'Content-Type': 'application/json'}

response     = requests.post(webhook_url, json.dumps(main_content), headers=headers)

It looks like this.

** The color of the left vertical bar is set with ** color ** in ** ʻembeds` ** **. The correspondence between numbers and colors is here. Move the "Color Mixer" bar to find the color you want to display and give it the number to the right of "Decimal:".  SS 2020-07-12 21.27.14.png

Make it a function and reuse it

For example, it looks like this. When sending only text, give arguments only for channel and content. If you want to use embedding, give the required information with ʻemb`.

emb = {
          'description': 'Embedded text',
          'color': 'color',
          'img_url': 'Image URL',
          'content': 'Text'
      }
def send_discord_msg(channel, content, emb=0):
    webhook_dic     = {'channel 1': 'webhook URL for channel 1', 
                       'channel 2': 'webhook URL for channel 2'}
    webhook_url     = webhook_dic[channel]

    main_content    = {
        'username': 'bot name',
        'avatar_url': 'Icon URL',
        'content': content
    }

    if emb != 0:
        color_dic = {
            'Color 1': 15146762,
            'Color 2': 49356,
        }
        embeds = [
            {
                'description': emb['description'],
                "color": color_dic[emb['color']],
                "image": {
                    "url": emb['img_url']
                },
            }
        ]
        main_content.update({'embeds': embeds})
        main_content['content'] = emb['content']

    headers = {'Content-Type': 'application/json'}
    try:
        res = requests.post(webhook_url, json.dumps(main_content), headers=headers)
    except Exception as e:
        print(e)

Recommended Posts

Create a discord bot that notifies unilaterally with python (use only requests and json)
Create a bot that only returns the result of morphological analysis with MeCab on Discord
[LINE Messaging API] Create a BOT that connects with someone with Python
Create a BOT that can call images registered with Discord like pictograms
Create a LINE BOT with Minette for Python
Create a page that loads infinitely with python
Steps to create a Twitter bot with python
[Python] Use JSON with Python
If you want to make a discord bot with python, let's use a framework
I made a LINE BOT with Python and Heroku
A template that I often use when making Discord BOT in Python (memorial note)
Create a directory with python
Create a Mastodon bot with a function to automatically reply with Python
Let's create a script that registers with Ideone.com in Python.
Let's create a PRML diagram with Python, Numpy and matplotlib.
Use a macro that runs when saving python with vscode
Create a Twitter BOT with the GoogleAppEngine SDK for Python
Create code that outputs "A and pretending B" in python
Tornado-Let's create a Web API that easily returns JSON with JSON
I want to use a wildcard that I want to shell with Python remove
[Python / Django] Create a web API that responds in JSON format
Create a striped illusion with gamma correction for Python3 and openCV3
Create a virtual environment with Python!
JSON encoding and decoding with python
Create a C ++ and Python execution environment with WSL2 + Docker + VSCode
Create a simple Python development environment with VS Code and Docker
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
Make a Discord Bot that you can search for and paste images
I made a Discord bot in Python that translates when it reacts
Create a record with attachments in KINTONE using the Python requests module
Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Create a decision tree from 0 with Python and understand it (5. Information Entropy)
I wrote a Slack bot that notifies delay information with AWS Lambda
[Python] A program that creates stairs with #
Create a dummy image with Python + PIL.
[Python] Create a virtual environment with Anaconda
Let's create a free group with Python
Create a JSON object mapper in Python
A memo with Python2.7 and Python3 on CentOS
Use PIL and Pillow with Cygwin Python
Create and decrypt Caesar cipher with python
[Python] [LINE Bot] Create a parrot return LINE Bot
Reading and writing JSON files with Python
Create a word frequency counter with Python 3.4
[Python] Create a LineBot that runs regularly
A typed world that begins with Python
Create a bot that boosts Twitter trends
Let's make a Twitter Bot with Python!
Use Python and MeCab with Azure Functions
Create an application that inputs, displays, and deletes forms by using an array as a DB with Python / Flask.
Word count that counts only words that start with a capital letter in python
I tried to create a class that can easily serialize Json in Python
Create a simple reception system with the Python serverless framework Chalice and Twilio
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
Create a frame with transparent background with tkinter [Python]
Discord bot with python raspberry pi zero with [Notes]
Make a Twitter trend bot with heroku + Python
Create an app that guesses students with python
Building a python environment with virtualenv and direnv
Read JSON with Python and output as CSV