Команда server discord py
Гайд для GitHub по написанию бота c помощью discord.py
Дата написания данного гайда 05.02.2021 Библиотека discord.py может обновляться, поэтому после крупных патчей разработка бота может отличаться. В любом случае ближайшие несколько месяцев данный гайд будет актуален.
Что нам потребуется?:
- Стабильное интернет соединение
- Неплохие знания Питона
- Умение "гуглить" и находить нужную информацию
- Среда для написания кода
Я советую для разработки бота создать отдельный сервер в Дискорде, где мы будем проверять нашего бота, потому что почти ни у кого не получается запустить сложный код с первого раза, а спамить другим не очень хочется.
Создание Application'a:
После создания Application'а мы должны перейти во вкладку Bot, а затем нажать на кнопку Add Bot.
Если у вас появилось зеленая надпись по типу: A wild bot has appeared!, значит вы всё сделали правильно и бот у вас уже создан.
Подключаем нашего бота к серверу:
Для того чтобы подключить бота к вашему серверу Дискорд, нужно следовать простым инструкциям:
Нужно получить Client_ID вашего бота. Для этого мы переходим во вкладку General Information и копируем его нажав на кнопку Copy.
Копируем эту ссылку ==> https://discordapp.com/oauth2/authorize?&client_id=(тут)&scope=bot&permissions=8 . В эту ссылку вместо слова "тут" вставляем наш Client_ID. Скобки естественно убираем. Доп. информация: В нашей ссылке bot&permissions=8 означает что наш permissions integer равен 8. Проще говоря, это число отвечает за то, какие права будут выданы боту при подключении. Этот код можно узнать во вкладке Bot (в которой мы создавали бота). Пролистав вниз, вы сможете сами выбрать нужные вам права, но я советую оставить 8, так как если вы будете сами выбирать права, могут произойти казусные ситуации при работе с ботом.
После создания нашей ссылки мы переходим по ней, выбираем сервер на который хотите пригласить бота и нажимаем кнопку Авторизовать. После прохождения капчи наш бот успешно присоединится к серверу, но будет оффлайн. Не пугайтесь, это нормально, ведь наш бот еще не запущен.
Создание проекта:
Ну вот мы и готовы начать писать код для нашего прекрасного бота. Если вы знаете Python на ОЧЕНЬ низком уровне, я советую воздержаться от создания ботов и заняться чем нибудь более простым.
Для начала я советую создать пустую папку где мы будем хранить все файлы для нашего бота.
Затем если у вас не установлена библиотека discord.py, вам нужно её устновить. Для этого переходим в командную строку и пишем: pip install discord.py
Внимание, для установки библиотек требуется pip, если он у вас не установлен, то гугл в помощь ^_^
После успешной установки библиотеки, переходим в вашу любимую среду разработки, в моём случае это PyCharm. Затем создаем новый файл Python файл с названием "bot" (такое название не даст вам запутаться) и расширением .py и сразу сохраняем его в нашей папке с проектом.
Первые строчки кода: Начинаем писать скрипт для нашего бота.
Для начала подключаем (импортируем) наши библиотеки:
(можем запустить наш скрипт для проверки работоспособности библиотеки)
Создаем еще один файлик .py названием config, для хранения в нём опасных данных. Почему мы не можем просто создать переменные с этими данными? Всё очень просто. Это самый простой способ защитить себя от злоумышленников. Если кто-то каким-то образом получит ваш код, то не сможет управлять вашим ботом. Все наши токены будут хранится в отдельном файлике.
В файле config.py создаем словарь, к которому мы будем обращаться при работе в ботом:
Сохраняем файл config.py и возвращаемся обратно к файлу bot.py
Импортируем наш файлик config.py:
Написание "тела" для бота и первый запуск:
Я буду стараться объяснять подробно каждый шаг и каждую строчку, потому что на первый взгляд это может показаться сложным, хотя таковым не является.
- Переменная bot - это "тело" нашего бота. Ему мы присваиваем значение commands.Bot с определёнными аргументами.
- command_prefix=settings['prefix'] - это аргумент, в который мы вписываем значение нашего префикса. settings['prefix'] означает, кто мы обращаемся к словарю settings (который мы импортировали из файла config.py) и обращаемся к ключу prefix, в котором вписано нужное нам значение.
Затем мы можем проверить, запускается наш бот или нет. В библиотеке discord.py есть огромное количество разных ивентов (Event). Одним из них мы сейчас воспользуемся:
@bot.event - говорит нам о том, что ниже будет прописана функция, являющаяся ивентом.
async def on_ready(): - Асинхронная функция (Очень важно все функции создавать асинхронными, так как бот должен выполнять несколько функций в одно время). Ей присваивается значение on_ready, данная функция срабатывает когда бот полностью подключен и готов к работе. Аргументов у этой функции нет.
Создание первой команды:
Настало время создать первую команду для нашего бота:
Можем запускать нашего бота и проверять команду!
Давайте создадим еще одну команду, но уже с использованием посторонней библиотеки. Я возьму библиотеку random. Для начала её нужно подключить. Переходим в cmd (командную строку) и пишем pip install random, после чего начнется скачка библиотеки. Затем в самом начале кода пишем:
Я создал очень простую команду, которая умеет генерировать случайное число от 0 до числа, которого мы зададим сами:
Точно так-же говорим о том что ниже будет команда с помощью строчки @bot.command. Напоиманаю, что bot - это перемеенная, которую мы создали в самом начале. Это наше "тело" для бота. Дольше создаем асинхронную функцию randoms. Почему не random? Потому что название функции не может совпадать с названием библиотеки. Дальше мы передаем 2 аргумеента: ctx и arg. В arg поместиться наше число, которое мы будем задавать. Дальше я использую try, вы спросите зачем? Всё просто. Если мы случайно укажем вместо числа какой-то другой символ, бот в чате выдаст ошибку. Затем мы создаем переменную a - это наше сгенерированное число. Как генерировать числа с помощью библиотеки random вы сможете найти выше по ссылке. Дальше с помощью await ctx.send мы выводим наше число.
Есть еще очень классная "фича" в библиотеке discord.py как стили embed. Их обычно используют для красивого вывода какой либо информации на экран. Например команды help обычно делают с использованием этого стиля. Я создал небольшую и довольно простую функцию, которая называется menu. В неё мы например можем записать каждую команду в боте и указать что она делает. Вот что у меня получилось:
Некоторые строчки я буду пропускать, потому что я их свойства и значения я объяснял выше. В любом случае если вы что-то не поняли я оставлял ссылку на доп. информацию в самом конце гайда. Для начала мы задаем переменную embed, в которой мы будем хранить сам "embed", а так-же его значения. Color - цвет, title - текст, который будет являться "названием". В них мы записываем нужны нам значения. Кстати в color мы так-же можем записывать цвет словами, например "yellow", "white" и так далее. Дальше мы прописываем add_field, эта штука добавляет нам новую "строку" для "embed". В значение name мы записываем имя строки, в value - значение ну и в inline указываем True или False, она меняет расположение строки. Советую поиграться и выбрать самый оптимальный для вас вариант. Последней строчкой в значении embed мы просто указываем переменную, которую мы задали в начале функции.
Есть еще несколько вещей, которые я хотел бы разобрать, но это я сделаю в будущем
P.S Возможно, я когда нибудь дополню этот гайд дополнительными интересными командами и ивентами.
I wrote this Code, everything seems fine, when I run the bot, there are no errors. The terminal is blank, but when I run this command, it doesn't work, it doesn't send a response, there is no error in the terminal also. Please Help..
Use print statements to see where the bot gets stuck. I also never heard of embed.Empty , what is this?
Markdown Text 101 (Chat Formatting: Bold, Italic, Underline)
Want to inject some flavor into your everyday text chat? You're in luck! Discord uses Markdown, a simple plain text…
At this point you can do allot. Any information you can get into Python (which is allot) you can style and print to the users. You can add allot of cool features just from using different API’s. Below are a couple other API’s that I have made commands with.
Integrate your service with Discord - whether it's a bot or a game or your whatever you wildest imagination can come up…
The following eight pictures will guide you through setting up you bot and adding it to your Discord server.
You should now be able to see your bot in the Discord server you added it too and it should have a little tag that says “Bot” next to it’s name.
Create a folder that you will use for bot and in it create a file called bot.py. We are going to start by adding the boilerplate code that is required.
But first we need to install discord.py with Python’s package manager called pip. You can do this by navigating to you Command Prompt in Windows and entering the following.
After this has completed successfully we can open our bot.py and begin. The code below imports the discord.py package that we just installed as well as creates our Discord client object that we will use to interact with the API. The token variable has our bot’s token that we copied earlier from the Discord developers page.
The client variable seen on line 4 is a Discord client object and will facilitate all the communication of the bot.
The on_ready() function above will be called when the bot starts and is connects to the API and will print the bot’s username, client ID, and the version of discord.py that is being used as seen beneath the try on line 12, 13, 14.
The on_message() function above will be called when ever a new message is posted in the Discord server and the message will be passed as the message variable seen entered as it’s only argument. As we have the function right now it will print that message to the console when received.
Try running this code, if it works you should see your bot’s username and client id printed in the console. If you go to the Discord channel that bot was added to and type a message you should see it appear in the console where you bot is running, you might also get an error directly after it which you can ignore for now.
So at this point our bot is able to read every message that is posted in it’s Discord server. To make this useful we need to implement some kind function that evaluates the messages that are posted. We can do this by making a command handler which will read each message, determine if a command is being called, and relay the appropriate response.
Although, before we make our command handler we have to decide on how we are going to organize our commands to make them easy to implement and visualize. My favorite way to do this in Python is by using dictionaries. Dictionaries allow us to define multiple labeled properties to a variable. An example is shown below.
The function above starting on line 2 will take in the parameters message, clients, and args. The variable message is an object with the details of the message, the client variable is also an object we need in the function to send messages with, the args variable is and array that will contain the arguments for function. This function will be used as a variable in our dictionary.
The Command Dictionary Parts
- trigger: is a string that will be what the command handler will look for.
- function: is a function that will be executed when it’s trigger is found.
- args_num: is an integer that marks the amount of args the function uses.
- args_name: is an array of strings that name the args for feedback purposes.
- description: is a string that describes what the command does.
We could just write an independent function that would handle these commands but there is a better way to do it, creating a class. This class will contain methods to add commands, store commands, and evaluate commands. The class would look like this…
The command_handler(self, message) method will be used to evaluate each message that is sent on the Discord server. It basically just sees if the message starts with a command trigger and if it does it executes it’s corresponding function. The following is a pseudo code breakdown of what the command handler is doing for each message posted in the server.
- Checks if the message starts with a command trigger, if it doesn’t it stops.
- If the message does start with a trigger if makes sure that the trigger is valid by comparing it to the command dictionary's trigger value, if it’s not it stops.
- If the trigger is valid it removes the trigger from the message string and splits it at the spaces making an array named args.
- Then it checks to see how many args the command’s function takes using the command dictionary's args_num value, if it’s zero it simply executes the function in the command dictionary’s function value. If the command needs more than zero args it makes sure that there are at least the required amount and it passes them to the command dictionary’s function.
Below is what all this code would look like together and should be completely functional.
This bot should have a fully functioning !hello command that takes in one argument.
So what we have now is a functional “platform” to expand on. In this step I will demonstrate some of the more advanced things you could do with this setup and some ways to make it more user friendly.
Note: I removed the !hello command from earlier because it useless.
In this example I added two new commands, !commands and !ip.
The !commands command will list all the available commands and there descriptions.
The !ip command will take in an argument called IP/Domain and it uses the Free IP-API and the Python 3 requests package to query the API with the given Domain or IP and returns information from the API response. The Python 3 json package is also needed to turn the API response into a Python dictionary which we can work with.
Also if you notice, you also can use the Discord formatting markdown shown in the link below to style your outputs, the **text** will show up as bold in Discord. You can also use Unicode Symbols to mark new lines (\n).
Discord API Docs for Bots and Developers
4. [Not a mistake, but quick tip]
ctx.guild.owner by itself will give a Member object, however as you put it in a f-string it will give an ugly representation (something like or something idk so instead do ctx.guild.owner.mention so it would actually show the owner of the server in mention format (however since its in an embed it won't actually ping them)
In all, you should have:
Edit: I forgot to mention that I have formatted your code a bit to adhere to PEP8 (as in no spaces around the = in function calls, etc.)
Hey one, hey all, and welcome to a basic Discord bot writing tutorial. This is a basic tutorial that doesn't cover coding in general, but rather how to work with the Discord.py (v1.0.0a) library and how to write a simple bot with it. General help can be found on the Discord API guild and in the documentation.
This tutorial assumes some prior knowledge of programming, and assumes you already have Python3.5 (and Pip) or later installed and added to your PATH.
With that, let's get to it.
As with most Python libraries, Discord.py can be installed with Pip. However, since we're using the rewrite (alpha) version, you also need to have Git SCM installed, so be sure to do that. After you have that installed (and, optionally, you're in whatever venv you want to use) just run the command
This will install Discord.py.
After we have that installed, we need to grab a bot token from Discord. A "token" is a string that you send to a server to authenticate with.
Go to this url and create a new application. The name you supply will be the name of your bot, but you can change that later. After you've made an application, you should be redirected to a page with all of the app's details on it. Scroll to the bottom of this page and press "create a bot user". You will then have a "click to reveal" link that shows you your bot's token. Make sure you keep track of this - we'll need that in a minute.
Before you close that page, be sure to review whether you want your bot to be public or not. If the box is ticked, then anyone with the invite link will be able to add your bot to their guild, but if left unticked, only you can add the bot to any given guild.
Adding your Bot
It's fairly important that you add your bot to the guild you want to test it on, and that's simple enough to do. On your application page, you should be able to see "client ID" near the top. Copy that value, and paste it into this website (officially recommended by Discord). This allows you to tick the permissions you want your invite link to have, and then spits it out to you nicely at the bottom for you to share with others, or use so you can add it to your own servers. Having done that, let's get the actual programming underway~
Finally, we can get to some coding.
Start off by making a new file. It doesn't matter what the name of it is, provided it's not "discord", since we'll be importing that in a second. From there, you can start to write your bot.
First off, we need to import the things that interface with Discord. There are two (technically four, but we're ignoring the autosharded versions) included clients with Discord.py. There's Client , and there's Bot . There's not too much of a difference between the two, but Bot has the ability to interface with the commands extention of Discord.py, which is super useful, since we'll be writing. well. commands. So let's import that.
As you can see from the above snippet, we've created a new bot with the command prefix of ? . The command_prefix argument can take one of three things: a list, a string, or a function (which takes bot and then message, and needs to return a list or string). The simplest way to use this is with a string, so that's what we'll cover now.
This snippet, though short, is a basic bot made in Python, and when run will bring your bot online. It won't do anything (because you've not told it to yet), but it is a valid bot
The basis of Discord.py is to have functions that are triggered by events. These events are all documented here, but I'll cover a couple of them now.
The first one of note is on_ready . This is event is triggered when the bot is online and ready to communicate with Discord's servers. It's usually used as a simple "everything's ready, boss" kind of statement, so you know what's happening. This can be included like so:
There's a few things of note here. First of all, the @bot.event line. This is how all events are notated in Discord.py. Commands have a different decorator, but we'll get to that. Secondly, you'll see that you have async def instead of the normal def that you may have used before. That's because Discord.py is asynchronous, which means that multiple functions can be running at the same time, without interrupting one another. You may have come across the term "threaded" before, and this is essentially like that - each function would be running in a different thread when fired.
The next event that you'll probably use is on_message . Unlike on_ready , this takes a parameter of a Message object, and will include the details of whatever message fired the event.
It's here that some people will start to see how to make commands. What you would do is compare the message's content with another string (the command name) and then perform actions based on that. Many other libraries are laid out like that, but Discord.py includes a syntax for writing commands in a much nicer way.
It's now that we'll start writing commands. There will be two included in this tutorial: a "ping" command, and an "echo" command.
Importantly, if you're going to keep your on_message event, you must include await bot.process_commands(message) at the bottom - this tells D.py that after you've done your message event stuff that the message should be processed as a command.
The "ping" command on some bots will just spit the word "pong" back out at you, but we're going to write it so it gives you the latency of the bot instead. Pay attention to the difference between how commands are written and how events are written.
That may look like a lot, but don't worry - I'll explain it all now.
Secondly, you have async def ping . In this, you have ping being automatically assigned as the name of the command, so you don't need to specify it otherwise.
After that, we have a docstring. The docstring will be read by Discord.py, and automatically included in the help command (one is automatically generated for you). If you include multiple lines, then only the first will be included unless you explicitly run help name instead of just help .
The next line is pretty straightforward - latency = bot.latency is something that's included in the client; a float of how many seconds of latency the bot has.
The next line is not so straightforward. await ctx.send(latency) . First of all, you have the await statement. This means that the async flow of the function needs to stop and spend some time doing whatever it is you said. And what you said is ctx.send(latency) . The latency part is simple enough, it's the text that's being sent to the user. ctx.send is a method that allows you to directly reply to whatever message was sent. Many things have a .send attribute, including channels and users, but just using ctx.send allows you to just reply in the same channel as the command was invoked in.
Looking at it, it's pretty simple, right?
The echo command is slightly more complicated, since it needs to read what the user said. Regardless, there's only a couple of differences in the command than before.
If you compare this to the other statement, then you'll immediately be able to see the difference is in the arguments for the command - (ctx, *, content:str) as opposed to (ctx) . The difference is simply because we're getting more information from the user than before. In the first example, the user simply needed to invoke the command, and that was it. In this example, the user not only needs to invoke the command, but give the bot something to echo back. The * argument means that all remaining values are captured into the next variable, and the content:str is simply the value and type that it should be captures into/as.
For example: if I ran ?echo a b c , then the value of content would be "a b c" . If I ran ?echo test , the value of content would be "test" .
Conversely, for async def example(ctx, first:str, second:str, *, third:str) , running ?example a b c d would fill first with "a" , second with "b" , and third with "c d" . Hopefully that should help you to see what significance the * argument has.
Full Bot and its Layout
When saved and run, this will act as a functional bot for you!
Well, there you have it. A simple introduction to writing bots using Python and Discord.py. This is expandable in whole, so you can keep adding commands to that file for as long as you want. However, what you have here is definitely functional as a Discord bot. I'm happy to have helped you.
Асинхронная библиотека discord.py содержит все что нужно для бота, с помощью нее даже можно работать с голосовыми каналами сервера. В этой статье я расскажу как создать простенького бота для вашего discord сервера.
The official home of the Python Programming Language
You will also need to go to the Discord website and create your bot, add it to a server, and grant it permissions. This can be done at the following link.
3. Unnecessary braces
On the second last line, I'm not sure why you have the <> wrapped around icon_url = . So get rid of those.
Also, the url=embed.Empty is completely unnecessary as well as it is the default value for embed.set_author() (see here). So get rid of that.
Собственно пишем бота
Устанавливаем discord.py с помощью pip:
После успешной установки создаем файл bot.py, где будем писать бота.
Импортируем все необходимое:
Создаем переменную с вашим токеном, про который я писал выше:
Хотя еще рано, но если вы захотите залить вашего бота на какой-нибудь сервер, то стоить побеспокоится о безопасности вашего токена.
Создаем тело бота:
Для начала сделаем простенькую команду, аргумент которой бот будет просто пересылать:
И в конце запускаем бота с вашим токеном:
В итоге должно получится вот такое:
Теперь необходимо добавить бота на сервер. Сделать это можно с помощью ссылки:
Число необходимых прав можно получить в разделе настроек бота.
Теперь можно запускать бота:
После нескольких секунд, можно заметить его в сети:
Получение токена и Client ID для вашего бота
Для получения токена и ID бота небходимо создать свое приложение и в разделе General Information скопировать Client ID.
А в разделе настроек создать бота и скопировать его токен. Задача не сложная, думаю все с этим справятся.
1. Indentation.
This is basic stuff. Indent every line after the async def server(ctx): line.
2. Read the documentation!
If you look at the documentation for guild, you can see that guild.text_channel_count and guild.voice_channel_count don't exist. Instead, you have to do len(guild.text_channels) and len(guild.voice_channels) instead.
2 Answers 2
At first glance, you're not indenting properly. I also have never heard of url = embed.Empty .
As an aside, I replaced the embed.set_author line embed.set_author(name = f'', icon_url = ) with embed.set_author(name = f'' icon_url = because it seemed to me like that was the line you wanted to display information about the author rather than the guild.
If resolving your indentation and removing url = embed.Empty doesn't do the trick, then you'll have to run debug print statements line by line until you isolate the troublesome line.
There are few things wrong here.
Заключение
Вот так можно легко запустить у себя на сервере бота. Как можно заметить библиотека делает практически все за тебя и остается только добавлять свой функционал с использованием python. В следующий раз я покажу как следить за событиями, подключатся к голосовым каналам (избегая проблем с linux и Windows), использовать роли и права участников и другое.
Discord has a wonderful API that allows you to creates bots that can join Discord servers and channels and help manage as well as add extra functionality for it’s users.
In this tutorial I will show you how to make a basic Discord bot written in Python 3 that will be able to take handle custom commands using the discord.py package available through pip.
Having a good editor can make the process of writing and debugging code in any language much easier. Some good free editors that I have personally used are PyCharm Community Edition and Sublime Text 3.
You will also need to make sure that you have Python 3 installed on you computer. If you are on Windows you can download an installer from the following link.
Читайте также: