Introduction to discord.py (2)

Introduction

I run an unofficial server for discord.py (although some developers). Questions are also accepted here. You can also create a personal channel and get support there for ** people who want long-term support **. If you would like to receive personal support, please enter from the invitation url below and DM to @ Sumidora # 8931. https://discord.gg/KPp2Wsu ** Please also ask questions about this article here **

About this article

This article is a step-by-step study of discord.py. First you will learn the basic writing method, and then you will learn the advanced content. 【series】

Introduction to discord.py (1) Introduction to discord.py (2)

Caution

** This article is for people who can do even a little Python. ** ** However, you can use it just by copying it, but you will not be able to write it after that, so if you want to create more individual functions, It is recommended to study using books, paiza learning, dot installation, Progate, Kyoto University textbook. I will. The book I recommend is Shingo Tsuji's [Python Startbook](https://www.amazon.co.jp/Python Startbook-Augmented Revised Edition-Tsuji-Shingo / dp / 4774196436 /).

The operating environment of the author

Python 3.8.0 Mac OS Catalina 10.15.2 discord.py-1.3.2

Use various events

Last time I introduced that there are many events in discord.py. In addition to the previously used ʻon_ready and ʻon_message, we will introduce major events. (What is written in parentheses is an argument.) ** Detailed explanation will be introduced at the time of appearance **

About how to write

Writing like List \ [discord.Reaction] means a list that contains discord.Reaction.

event name Contents Remarks
on_message(message) Message was sent
on_message_delete(message) Message deleted I don't know who deleted it.Also, it is not called by deleting the message before the bot starts.
on_message_edit(before, after) Message updated Not called by message updates before the bot starts.
on_reaction_add(reaction, user) Reaction was attached Not called by adding to the message before the bot starts.
on_reaction_remove(reaction, user) Reaction deleted Not called by deleting to message before bot launches.
on_member_join(member) The user entered the server
on_member_remove(member) The user has left the server
on_voice_state_update(member, before, after) Voice status changed Called when entering, exiting, or muting a voice channel

As an example, here is the code that sends the content to the channel you set when the message was deleted:

import discord
client = discord.Client()


@client.event
async def on_message_delete(message):
    channel = client.get_channel(DEBUG_CHANNEL_ID)
    await channel.send(f"{message.author.name}Message has been deleted:\n```\n{message.content}\n```")


client.run(TOKEN)

Change server settings

The discord.py represents the server in the discord.Guild class. By acquiring this using Client, various changes can be made.

What to learn in this chapter

--How to get the server

Get the server

Get from id

Use the Client.get_guild or Client.fetch_guild functions. In the normal case, use the get_guild function.

# get_guild
guild = client.get_guild(GUILD_ID)

# fetch_guild
guild = await client.fetch_guild(GUILD_ID)

Get from name

To get it from the name, use the get function in discord.utils.

guild = discord.utils.get(client.guilds, name="name")

** Please note that this will only return the first one even if it has the same name **

Change server settings

The server setup is very long, so I will only show you the main one.

Rename

If you want to change the name etc. in discord.Guild, use the edit function.

#Continued above
await guild.edit(name="New name")

Change the description

Change the description.

#Continued above
await guild.edit(description="This is a descriptive note This is a descriptive note This is a descriptive note This is a descriptive note")

change icon

You can specify bytes for icon.

#Continued above

#Make a local file an icon
with open("test.png ", "rb") as f:
    await guild.edit(icon=f.getvalue())

Give a reason for change

These changes remain in the system log, but you can set the reason for viewing them at that time.

#Continued above

await guild.edit(name="Madomagi Ski Room", reason="I did it in my mood,I was not reflecting")

Change all at once

All the changes mentioned above can be done in one go.

#Continued above

await guild.edit(name="Madomagi Ski Room", description="A server where people who like Madomagi gather.", reason="I did it in my mood,I was not reflecting")

Change channel settings

The main classes that represent channels in discord.py are discord.CategoryChannel, discord.TextChannel, discord.VoiceChannel. By acquiring this using Client or Guild, various changes can be made.

What to learn in this chapter

--How to get the channel

Get the channel

Get from id

Use the Client.get_channel function or the Client.fetch_channel, Guild.get_channel functions. The get_channel function is usually used.

channel = guild.get_channel(CHANNEL_ID)

Get from name

To get it from the name, use the get function in discord.utils. In this case, you also need to pay attention to the type of channel. Use guild.channels, guild.text_channels, guild.voice_channels, guild.categories properly.

When acquiring from the text channel

Use guild.text_channels.

channel = discord.utils.get(guild.text_channels, name="name")

When acquiring from the voice channel

Use guild.voice_channels.

channel = discord.utils.get(guild.voice_channels, name="name")

When acquiring from the category

Use guild.categories.

channel = discord.utils.get(guild.categories, name="name")

When getting from all

Use guild.channels.

channel = discord.utils.get(guild.channels, name="name")

Change channel settings

The channel settings are very long, so I will only introduce the main one.

Text channel

Rename

Use name.

await channel.edit(name="New Name")

Change topic

Use topic.

await channel.edit(topic="topictopictopictopictoping")

Change location

use position

await channel.edit(position=2)

Change category

Use category.

#Set category
category_channel = client.get_channel(CATEGORY_CHANNEL_ID)
await channel.edit(category=category_channel)

#Remove categories
await channel.edit(category=None)

Change all at once

All the changes mentioned above can be done in one go.

await channel.edit(name="Notice", topic="運営からのNoticeを載せます.", category=None)

Change job title settings

It is the discord.Role class that represents the job title in discord.py. By getting this from the guild, you can make various changes. ** Permission changes will be introduced in a later chapter **

What to learn in this chapter

――Various setting methods for job titles

Get a job title

Get from id

Use the discord.Guild.get_role function.

guild = message.guild
role = guild.get_role(ROLE_ID)

Get from name

To get it from the name, use the get function in discord.utils.

guild = message.guild
role = discord.utils.get(guild.roles, name="name")

** Please note that this will only return the first one even if it has the same name **

Rename

To change the name, color, etc. in discord.Role, use the edit function.

#Continued above

#Rename
await role.edit(name="New name")

Change color

Use discord.Color to change the color. discord.Color has a function for each color, and you can also use it.

#Continued above

#When using RGB
await role.edit(colour=discord.Colour.from_rgb(256, 256, 256))

#When using hsv(H,S,Give each V a value between 0 and 1)
await role.edit(colour=discord.Colour.from_hsv(0, 0, 1))

#When using a function
await role.edit(colour=discord.Colour.blue())

Change position

When changing the position, it is necessary to put the numerical value of the position in the position argument. Since 0 is @everyone, you need to choose 1 or more. It goes up in order from 1.

#Continued above

await role.edit(position=1)

Give a reason for change

These changes remain in the system log, but you can set the reason for viewing them at that time.

#Continued above

await role.edit(position=1, reason="I did it in my mood,I was not reflecting")

Change all at once

All the changes mentioned above can be done in one go.

await role.edit(name="Lush green", colour=discord.Colour.green(), position=1, reason="I did it in my mood,I was not reflecting")

Change permissions

Study in this section

--About discord.py permissions --How to change the authority of a job title --How to change channel permissions

Classes around permissions in discord.py

The classes around the permissions of discord.py are discord.Permissions and discord.PermissionOverWrite. Each of these is linked to discord job title permissions and per-channel settings.

Regarding the value that can be set for each item, Permission can only be set on and off, while PermissionOverWrite can be "not set" in addition to on and off (if not set, higher authority setting, for example, if it is a text channel, it belongs to Inherit the settings of the category channel to be set).

Also, there is a difference between the two that Permissions overwrites everything (other than the one you did not specify will be changed), while PermissionOverWrite overwrites only the specified one.

# overwrite
overwrite = discord.PermissionOverWrite()
overwrite.read_messages = True
overwrite.manage_messages = False
overwrite.send_messages = None  #None can be set with overwrite

# permissions
permissions = discord.Permissions()
permissions.read_messages = True
permissions.manage_messages = False
# permissions.send_messages = None #None cannot be set

Change job title authority

In discord.py, the job title is discord.Role. First, you need to get this from the guild.

Get from id

Use the discord.Guild.get_role function.

guild = message.guild
role = guild.get_role(ROLE_ID)

Get from name

To get it from the name, use the get function in discord.utils.

guild = message.guild
role = discord.utils.get(guild.roles, name="name")

** Please note that this will only return the first one even if it has the same name **

Get the authority to change to

To change the permissions, you need to create a new discord.Permissions class. Here, use the permissions of the role once acquired to avoid unnecessary changes.

guild = message.guild
role = discord.utils.get(guild.roles, name="everyone")
#Get permissions
permissions = role.permissions

To change the value of discord.Permissions, you need to put Allow = True or Prohibit = False in the variable corresponding to the name of the permission.

#Continued one level above

# @Make everyone beat
permissions.mention_everyone = False

#Add change permission for emoji
permissions.manage_emojis = True

Create new Permissions

If you want to create a new one, you can create it by setting permissions = discord.Permissions ().

change

To reflect this in discord.Role, use the discord.Role.edit function (** coroutine function **) As I did last time, with the edit function, you can set the name, color, whether it is displayed separately from everyone, and the position.

#Continued above

await role.edit(permissions=permissions)

Change channel permissions

Change channel permissions using set_permissions.

When setting permissions directly

You can change the permissions of users and job titles by using the set_permissions command.

channel = client.get_channel(CHANNEL_ID)
#Get the target member
member = channel.guild.get_member(MEMBER_ID)

#change
await channel.set_permissions(member, send_messages=False)

When using PermissionOverWrite

You can use PermissionOverWrite to set compliance with the None = category setting.

channel = client.get_channel(CHANNEL_ID)
#Get the target job title
role = discord.utils.get(channel.guild.roles, name="everyone")

overwrite = discord.PermissionOverWrite()
overwrite.send_messages = False
overwrite.read_messages = None

#change
await channel.set_permissions(role, overwrite=overwrite)

Create a channel

What to learn in this chapter

--How to create a channel

How to create a text channel

To create a text channel, use the discord.Guild.create_text_channel or discord.CategoryChannel.create_text_channel function. If you use discord.CategoryChannel.create_text_channel, it will automatically belong to the parent category. In discord.Guild.create_text_channel, you have to set it yourself. You can also set permissions together, but you can only use PermissionOverWrite. When setting permissions,

{
Job title or member to specify- :Corresponding PermissionOverWrite,
    guild.me :Corresponding PermissionOverWrite
}

Use it like this.

# discord.Guild.create_text_use channel
guild = client.get_guild(GUIILD_ID)
# @Everyone can't speak, but I can
overwrites = {guild.default_role: discord.PermissionOverWrite(send_messages=False),
              guild.me: discord.PermissionOverWrite(send_messages=True)
}
new_channel = await guild.create_text_channel(name="Notice", overwrites=overwrites, topic="Noticeを表示します。")
print(f"#{new_channel.name}is created.")

The return value of create_text_channel is the newly created channel.

How to create a voice channel

It's basically the same as a text channel, but without topic and slow mode settings.

# discord.Guild.create_voice_use channel
category = client.get_channel(CATEGORY_ID)
await category.create_voice_channel(name="Chat voice")

How to create a category

Here you can only set the name and permissions. Also, there is only discord.Guild.create_category.

guild = client.get_guild(GUIILD_ID)
# @I can't see everyone, but I can see
overwrites = {guild.default_role: discord.PermissionOverWrite(read_messages=False),
              guild.me: discord.PermissionOverWrite(read_messages=True)
}
await guild.create_category(name="For operation", overwrites=overwrites)

At the end

How was it so far? This time, I explained how to write by dividing it into how to use advanced events, how to change settings, and how to create channels. In the next article, we will discuss how to wait for input and how to connect to a voice channel and play audio. Well then. The next article is being produced in good faith.

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 Supervisor
Introduction to Scrapy (2)
[Linux] Introduction to Linux
Introduction to discord.py (1st day) -Preparation for discord.py-
Introduction to Lightning pytorch
Introduction to Web Scraping
Introduction to EV3 / MicroPython
Introduction to Python language
Introduction to TensorFlow-Image Recognition
Introduction to OpenCV (python)-(2)
Introduction to PyQt4 Part 1
Introduction to Dependency Injection
Introduction to Private Chainer
Introduction to machine learning
AOJ Introduction to Programming Topic # 1, Topic # 2, Topic # 3, Topic # 4
Introduction to electronic paper modules
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
Deep Reinforcement Learning 1 Introduction to Reinforcement Learning
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 ~