- Saved searches
- Use saved searches to filter your results more quickly
- Tasfers/discord_bot
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Adding Discord Bot Status with Python
- How to add it?
- Example code
- How To Create A Changing Status & Activity In Discord Py
- Step 1 – Getting Started
- Step 2 – Setting Up A Task
- Кастомный статус с кнопками в Discord. (Python)
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Гайд по написанию Discord бота на языке Python
Tasfers/discord_bot
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Гайд по написанию дискорд бота на языке Python и на библиотеке Disnake
Для корректной работы бота советуем установить Python 3.9 и выше
- Тыкаем сюда и у вас скачивается Python 3.9
- Обязательно включаем галочку рядом с Add Python 3.9 to PATH и проходим дальнейшую установку
После установки Python вы так же можете установить Visual Studio Code для редактирования файлов бота по этой ссылке
- Заходим на сайт и нажимаем на кнопку New Application
- Вводим название приложения и нажимаем Create
- Выбираем вкладку Bot
- Нажимаем Add Bot
- И снова нажимаем Yes, do it!
- Нажимаем Reset Token и сохраняем его где-нибудь (После перезагрузки страницы токен пропадет и его придется пересоздать в случае утери)
Во вкладке Bot включаем следующие галочки
- Public Bot — Означает, что бот является общедоступным и может быть добавлен другими людьми на их сервера в Discord.
- Presence Intent — Позволяет боту отслеживать присутствие пользователей, включая их статус в реальном времени (например, онлайн, отсутствует, занят) и активность (например, играет в игру).
- Server Members Intent — Позволяет боту получать информацию об участниках сервера, такую как имена, никнеймы, роли и т.д.
- Message Content Intent — Позволяет боту получать информацию о содержимом сообщений, включая текст и вложения.
Пишем в cmd вот эту команду pip install disnake
Онлайн status=disnake.Status.online Оффлайн status=disnake.Status.offline Не беспокоить status=disnake.Status.dnd Не активен status=disnake.Status.idle
Играет activity=disnake.Game(name="игру") Смотрит activity=disnake.Activity(type=disnake.ActivityType.watching, name="ютуб") Слушает activity=disnake.Activity(type=disnake.ActivityType.listening, name="музыку") Стримит activity=disnake.Streaming(name="игру", url="https://www.twitch.tv/никнейм") #если убрать аргумент url то кнопки просто не будет, но все будет работать Соревнуется в activity=disnake.Activity(type=disnake.ActivityType.competing, name="создании бота")
Этот параметр обозначает добавление тестового сервера на котором слеш команды будут обновляться сразу При добавлении большого количество идентификаторов то бот будет запускаться медленно, советуем добавлять не более 3х
Что бы добавить туда свой сервер напишите так
test_guilds=[960169222808432660]
Что бы добавить несколько серверов напишите так
test_guilds=[960169222808432660, 941767647790514216]
Важно — Если айди вашего сервера не будет там то слеш команда появится/обновится только через 10-15 минут после её добавления/изменения
Создаем файл .py в папке cogs , пример — moderation.py
Начинка кога (Вместо Fun ставим название своего кога)
import disnake from disnake.ext import commands class Fun(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_ready(self): #ивент который будет активироваться когда вы включите бота print('Любой текст, к примеру: Cog Fun - Ready') #Тут будут команды и ивенты def setup(bot): bot.add_cog(Fun(bot))
Ког — модуль бота где хранятся команды, можно создавать столько когов, сколько захотите (Модерация, Развлечение и.т.п)
Токен — зашифрованный ключ Discord, с помощью которого бот авторизуется
Импорт — обязательная вещь которая добавляет в код много полезного, пример ниже
import disnake from disnake.ext import commands
Ивент — триггер который активируется при каком либо действии, к примеру on_ready — бот включен(готов)
На этом все, дальше смотрите файлы, там я буду выкладывать примеры
About
Гайд по написанию Discord бота на языке Python
Adding Discord Bot Status with Python
We all have seen a custom status on a discord bot like ‘playing a game’ or ‘watching a movie’, that is known as ‘Rich Presence’. We have to enter some lines of code to add a custom rich presence in a Discord Bot. This Post will help you to add a custom rich presence in your discord bot.
How to add it?
To add this, import discord and commands. The client object for the bot has a method change_presence . This is used to change the status of your bot! • For Playing: Use discord.game() for adding playing status. Add the name of the game to the name argument
import discord from discord.ext import commands client = discord.Client() @client.event async def on_ready(): await client.change_presence(status=discord.Status.Online, activity=discord.game('a video game')) print('We have logged in as '.format(client))
Note: Discord only supports streaming links for YouTube and Twitch. The url argument must be formatted as an actual URL. http://www.twitch.tv will work while www.twitch.tv will not. It won’t change the bot status at all.
import discord from discord.ext import commands client = discord.Client @client.event async def on_ready(): await client.change_presence(activity=discord.Streaming(name='a movie', url='https://www.twitch.tv/your_channel_here')) print('We have logged in as '.format(client))
• For Watching: Use discord.Activity() with the type argument set to discord.ActivityType.watching for the watching status.
import discord from discord.ext import commands client = discord.Client @client.event async def on_ready(): await client.change_presence(activity=discord. Activity(type=discord.ActivityType.watching, name='A Movie')) print('We have logged in as '.format(client))
• For Listening: Use discord.Activity() with the type argument set to discord.ActivityType.listening for the listening status.
import discord from discord.ext import commands client = discord.Client @client.event async def on_ready(): await client.change_presence(activity=discord. Activity(type=discord.ActivityType.listening, name='To Music')) print('We have logged in as '.format(client))
Example code
import discord from discord.ext import commands # Change below's prefix with your prefix client = commands.Bot(command.prefix = 'ENTER YOUR PREFIX') @client.event async def on_ready(): await client.change_presence(status=discord.Status.Online, activity=discord.game('a video game')) # You can change the current status above client.run('Your Bot Token')
How To Create A Changing Status & Activity In Discord Py
Create a changing looping status task for your discord.py or all other forks of discord.py such as disnake, pycord, etc. All types of status types included.
This article includes all types of activities and Statuses usable in a discord bot. So, let’s get started…
Step 1 – Getting Started
First of all setup the basic bot. Additionally you can check the example.py [if you are using other forks of discord.py then just change the “discord” text from all the over the codes into that fork’s name]
Also make sure to import these:
import discord
import asyncio
from discord.ext import tasks, commands
from discord.ext.commands import Bot
from discord.ext.commands import Context
Step 2 – Setting Up A Task
First of all in bot event: on “on_ready” event, include a new line “status_task.start()“, [if you not added “on_ready” event, then add:
@bot.event()
async def on_ready():
status_task.start() #to start the looping task
Then we need to setup the task. now after that add this structure:
@tasks.loop()
async def status_task() -> None:
#put the upcoming codes here
Now let’s complete the code:
await bot.change_presence(status=STATUS-HERE, activity=ACTIVITY-HERE)
await asyncio.sleep(TIME)
This is the main format and by adding this multiple times you will be able to create a looping task. We just need to change the “STATUS-HERE” and “ACTIVITY-HERE” text to set a status with custom activity. Here’s the list of all available Statuses:
discord.Status.dnd #To set status to DND
discord.Status.idle #To set status to Idle
discord.Status.online #To set status to Online
Here’s The List of all Available Activity Types:
#streaming Activity.
discord.Streaming(name="stream name", url="stream url")
# Gaming Activity.
discord.Game("Name of the Game")
#listening Activity
discord.Activity(type=discord.ActivityType.listening, name="name of the music")
#watching Activity
discord.Activity(type=discord.ActivityType.watching, name="name of the movie")
To understand the codes better, you may check the “example.py” from my GitHub repository:
Thanks For Allowing Us To Help You!
If you are confused or want to know something, then let us know in the comment box, we will reach you as soon as possible. Don’t Forget To Subscribe our Newsletter, YouTube Channel, and Like Our Facebook Page To Keep Updated With Awesome Things. Follow us on Twitter to stay updated with the latest news & changes.
Mahedi Zaman Zaber
I’m a Driven and ambitious individual who is currently pursuing a Bachelor of Science in Computer Science and Engineering. With a passion for innovation and a desire to make a lasting impact, I aspire to become a distinguished software engineer and entrepreneur.
Кастомный статус с кнопками в Discord. (Python)
Если все выше сказанные пункты выполнены перейдем к реализации кастомного статуса.
1. Что нужно сделать — это зайти на Discord Developers и создать новое приложение:
Здесь пишите название приложения, оно будет отображаться первым в нашем будущем статусе. (В примере выше — Ghoul)
2. Установка библиотеки pypresence.
Открываем командую строку или powershell или любую другую консоль. (Я буду использовать
После установки pypresence, переходим в корневую папку python — libs — site-packages — pypresence
И перекидываем последнюю версию с гитхаба в папку pypresence с заменой. (Т.к. с pypi не всегда скачивается стабильная версия и может что-то не работать)
Мой путь к папке pypresence:
C:\Users\mlwrx\AppData\Local\Programs\Python\Python39\Lib\site-packages\pypresence
И обязательно удаляем папку __pycache__ в избежание ошибок.
3. Реализация кастомного статуса.
Создаем файл с разрешением .py в моем случае это — script.py.
Переходим к написанию кода.
from pypresence import Presence from time import time RPC = Presence("client id") btns = [ < "label": "VK", "url": "link" >, < "label": "TG", "url": "link" >] RPC.connect() RPC.update( state="zxc?", details="SSS Rank", start=time(), buttons=btns, large_image="kanekicheln", small_image="kaneki", large_text="Я гуль." ) input()
Так должен выглядить код в итоге.
Сейчас разберем по полочкам каждую переменную.
Подключение библиотек.
from pypresence import Presence from time import time
Берем CLIENT ID и вставляем в код.
Наши кнопки: (В моем случае ссылка на VK и TG)
RPC.connect() // Подключение RPC.update( state="zxc?", // 3 строка в статусе details="SSS Rank", // 2 Строка в статусе start=time(), // Таймер запуска приложений buttons=btns, // Подключение кнопок large_image="kanekicheln", // Название большой картинки(Ниже объясню куда загружать их) small_image="kaneki", // Название маленькой картинки (Ниже объясню куда загружать их) large_text="Я гуль." // Надпись на большой картинке при наведении. (Так же можно сделать и надпись на маленькой картинки, добавив переменную small_text) ) input() // Чтобы не закрывалась консоль (Не трогаем)
4. Итак нам осталось загрузить картинки для статуса и поставить аватарку боту.
— Переходим все на тот же
— Нажимаем Add Images и заливаем картинки. (P.S. заливаются не сразу. Нужно подождать 5-10 минут.)
5. Если все правильно сделали и настроили скрипт, то сохраняем его и запускаем. Если не выдало ошибок, то сделали все правильно. (Большинство ошибок фиксится удалением __pycache__. Выше показывал где удалять.)
Что получилось у меня:
Сами вы кнопки нажать не можете, только другие пользователи дс.
На этом тема подходит к концу, буду рад, если помог и тема была интересна.
Контакты для связи:
Telegram.
Если что-то не получается — пишите, помогу.