[PYTHON] Introduction to discord.py

Template

The template is the part that becomes the pattern when writing the program code.

Discord.py template

import discord
token = "" #Assign token here
client = discord.Client()

#What to do when the bot is ready
@client.event
async def on_ready():
    print("ready")

#Write other processing below from here ↓


# —-So far--


client.run(token)

Event handler

An event handler is a function that separates processing for each event that occurs on discord. 677FBF82-E001-466D-AAE7-4FF69604AD33.jpeg

The event handler description method is as follows.

@client.event
async def event handler name(argument):
processing

Main event handlers

Event handler name argument Explanation
on_message message Events that occur when a message is sent
add_reaction reaction,user Occurs when a reaction is given to a message
on_member_join member Occurs when a member joins the server.

Note If you register the same event handler more than once, it will not work.

ex)

#Bad example
@client.event
async def on_message(message):
processing

@client.event
async def on_message(message):
processing

Event handler reference discord.py API refarence

type of discord.py

discord.py has its own types like str and int

Main types

discord.Message The information of the message is organized, Main attributes

attribute Explanation Return type
content Returns the content of the message str
author Returns the sender of the message discord.User
channel Returns the channel that sent the message. discord.TextChannel
id Returns the ID of the message. int
guild Returns the server to which the message was sent discord.Guild

Reference

discord.TextChannel Information on the text channel is collected Main attributes

attribute Explanation Return type
name Returns the channel name. str
id Returns the ID of the channel. int
category Returns the category in which the channel exists discord.CtegoryChannel
guild Returns the server where the channel resides. discord.Guild
members Returns a list of channel members. list[discrd.Members]

Reference

discord.Role Information on roles is collected.

Main attributes

attribute Explanation Return type
name Returns the role name str
id Returns the ID of the role int
members Returns the list of members with the role list[discord.Member]
color Returns the color of the roll discord.Colour
permissions Returns the permissions of the role. discord.Permissions

Reference

discord.Member Information on members is collected.

attribute Explanation Return type
name Returns the user's name str
id Returns the user's ID int
avatar_url Returns the URL of the user's avatar discord.Asset
roles Returns the role list that the user has list[discord.Role]
guild Returns the server where the member resides discord.Guild
status Returns the status of the member. discord.Status

Reference

Operate discord

Each type has a method for sending messages and granting roles, as well as a Attribute. From the following, I will explain the methods and list the methods that are often used.

About await

The type of discord.TextChannel has a methodsend ()that sends a message. Also, the type of discord.Guild has a methodget_channel (channel ID)to get the channel.

I will summarize the outline of each method for the time being

Type with method Method Method arguments Method return value
discord.TextChannel send content(str)... discord.Message
discord.Guild get_channel Channel ID(int) abc.GuildChannel
@client.event
async def on_message(message):
    send_message = "I received a message." #Message content
    guild = message.guild #The server to which the message was sent
    channel = guild.get_channel(00000000000) #Get channel
    await send_channel.send(send_message)#Send message

The send () method used on line 6 has a await. On the other hand, the get_channel method used in line 5 does not have await.

From here, I will explain about this await, If it's difficult, there may be some misunderstandings, but operate it in a visible way on discord. ex (send message, add reaction, create channel

Imagine that things need await.

On the contrary, getting a channel, checking if the user is a friend, etc. Interpret that await is not attached to the method that performs processing such as acquiring information.

Explanation of await

await is prefixed when the function to be executed is a coroutine This is called the async/await syntax.

Functions with async are called coroutine functions,

What is a coroutine function?

Normal functions are executed as synchronous processing. In other words, if function B is executed while function A is being executed, the processing of function A will be interrupted and the processing of function B will start. As soon as function B finishes, processing of function A resumes. D06E1A4F-22BD-47E9-A2D7-F7F76502950A.jpeg

However, the coroutine function is executed as an asynchronous process, You can run a task in parallel with another process. CFD37752-AC43-4E8C-9DA5-9001EF27737F.jpeg

import time

def wait_A():
    print("Start process A")
    time.sleep(1)
    print("End process A")

def wait_B():
    print("Start process B")
    time.sleep(2)
    print("End process B")

def wait_C():
    print("Start process C")
    time.sleep(3)
    print("End process C")

if __name__ == "__main__":
    wait_A()
    wait_B()
    wait_C()

Run this program.

~output~
Start process A
End process A
Start process B
End process B
Start process C
End process C

It will be.

Define this as a coroutine function

import asyncio
async def wait_A():
    print("Start process A")
    asyncio.sleep(3)
    print("End process A")

async def wait_B():
    print("Start process B")
    asyncio.sleep(2)
    print("End process B")

async def wait_C():
    print("Start process C")
    asyncio.sleep(1)
    print("End process C")

if __name__ == "__main__":
    await wait_A()
    await wait_B()
    await wait_C()

output
Start process A
Start process B
Start process C
End process C
End process B
End process A

It will be.

You can see that we are running multiple processes in parallel.

In other words, in the discord.py module You need to add await if the method of type was defined as a coroutine function.

You need to check the discord.py documentation to see if the type method is defined as a coroutine function or not. BD2BC61E-B3D0-4CEC-A665-494593BE6A3B.png

There is a Method item at the beginning of each type description. Those with async at the beginning of the list are coroutine function methods.

Send various messages

Embedded message

@client.event
async def on_message(message):
    if message.content == "/embedded":
        send_embed = discord.Embed(title="Embedded title",description="Embedding description",colour=discord.Colour.red())
        send_embed.add_field(name="Field name",value="Field description")
        await message.channel.send(embed=embed)

discord.Embed is a data class for discord.py. You can instantiate the data class on line 4 and specify the title, description, and color. add_field is a method of the Embed data class, not a coroutine function. In addition to the name and value arguments, add_field has an argument called inline, which can have a bool value. The default value for inline is True Display side by side with other fields. When inline = False is set Display the field vertically.

Send the image.

await message.channel.send(File=discord.File("sample.png "))

File can be specified as the argument of send, The File argument specifies the data class of discord.File. When instantiating the File argument, you can send the image directly by specifying the file path as a string type.

1/8 updated

Recommended Posts

Introduction to discord.py (2)
Introduction to discord.py
Introduction to discord.py (3) Using voice
Introduction to MQTT (Introduction)
Introduction to Scrapy (1)
Introduction to Scrapy (3)
Introduction to Tkinter 1: Introduction
Introduction to PyQt
[Linux] Introduction to Linux
Introduction to Scrapy (4)
Introduction to discord.py (1st day) -Preparation for discord.py-
Introduction to Lightning pytorch
Introduction to Web Scraping
Introduction to Nonparametric Bayes
Introduction to EV3 / MicroPython
Introduction to Python language
Introduction to TensorFlow-Image Recognition
Introduction to PyQt4 Part 1
Introduction to Dependency Injection
Introduction to Private Chainer
Introduction to machine learning
A quick introduction to pytest-mock
Introduction to dictionary lookup algorithm
Introduction to Monte Carlo Method
[Learning memorandum] Introduction to vim
Introduction to PyTorch (1) Automatic differentiation
opencv-python Introduction to image processing
Introduction to Python Django (2) Win
Introduction to Cython Writing [Notes]
An introduction to private TensorFlow
Kubernetes Scheduler Introduction to Homebrew
An introduction to machine learning
[Introduction to cx_Oracle] Overview of cx_Oracle
A super introduction to Linux
Introduction
AOJ Introduction to Programming Topic # 7, Topic # 8
[Introduction to pytorch-lightning] First Lit ♬
Introduction to Anomaly Detection 1 Basics
Introduction to RDB with sqlalchemy Ⅰ
[Introduction to Systre] Fibonacci Retracement ♬
Introduction to Nonlinear Optimization (I)
Introduction to serial communication [Python]
AOJ Introduction to Programming Topic # 5, Topic # 6
Introduction to Deep Learning ~ Learning Rules ~
[Introduction to Python] <list> [edit: 2020/02/22]
Introduction to Python (Python version APG4b)
An introduction to Python Programming
[Introduction to cx_Oracle] (8th) cx_Oracle 8.0 release
An introduction to Bayesian optimization
Super introduction to machine learning
Introduction to Ansible Part ③'Inventory'
Series: Introduction to cx_Oracle Contents
[Introduction] How to use open3d
Introduction to Python For, While
Introduction to Deep Learning ~ Backpropagation ~
Introduction to Ansible Part ④'Variable'
Introduction to vi command (memorandum)
Easy introduction to home hack with Raspberry Pi and discord.py
Introduction to Linux Commands ~ LS-DYNA Edition ~
[Introduction to Udemy Python 3 + Application] 58. Lambda
Introduction to Ansible Part 2'Basic Grammar'