Перейти к содержимому

Как установить библиотеку discord py в python

  • автор:

Переход на Discord.py 2.0

В общем, писала бота +- на discord.py 1.7.3 или что то вроде, недавно отказали эти библиотеки и пришлось обновляться. Как итог полный отказ работы бота. Узнала про изменения когов и тп, щас бот запускается, некоторые команды даже работают, меняется статус. Но по большей части команды все же не работают, мне не понятно почему, ибо ни слова нету в терминале. Как будто ошибок нет. Что нужно поменять чтобы это прекратилось? xd

Отслеживать

Eternity Halcyon

задан 1 окт 2022 в 7:36

Eternity Halcyon Eternity Halcyon

44 4 4 бронзовых знака

Пожалуйста, уточните вашу конкретную проблему или приведите более подробную информацию о том, что именно вам нужно. В текущем виде сложно понять, что именно вы спрашиваете.

Introduction¶

This is the documentation for discord.py, a library for Python to aid in creating applications that utilise the Discord API.

Prerequisites¶

discord.py works with Python 3.8 or higher. Support for earlier versions of Python is not provided. Python 2.7 or lower is not supported. Python 3.7 or lower is not supported.

Installing¶

You can get the library directly from PyPI:

python3 -m pip install -U discord.py 

If you are using Windows, then the following should be used instead:

py -3 -m pip install -U discord.py 

To get voice support, you should use discord.py[voice] instead of discord.py , e.g.

python3 -m pip install -U discord.py[voice] 

On Linux environments, installing voice requires getting the following dependencies:

For a Debian-based system, the following command will get these dependencies:

$ apt install libffi-dev libnacl-dev python3-dev

Remember to check your permissions!

Virtual Environments¶

Sometimes you want to keep libraries from polluting system installs or use a different version of libraries than the ones installed on the system. You might also not have permissions to install libraries system-wide. For this purpose, the standard library as of Python 3.3 comes with a concept called “Virtual Environment”s to help maintain these separate versions.

A more in-depth tutorial is found on Virtual Environments and Packages .

However, for the quick and dirty:

    Go to your project’s working directory:

$ cd your-bot-source $ python3 -m venv bot-env
$ source bot-env/bin/activate

On Windows you activate it with:

$ bot-env\Scripts\activate.bat
$ pip install -U discord.py

Congratulations. You now have a virtual environment all set up.

Scripts executed with py -3 will ignore any currently active virtual environment, as the -3 specifies a global scope.

Basic Concepts¶

discord.py revolves around the concept of events . An event is something you listen to and then respond to. For example, when a message happens, you will receive an event about it that you can respond to.

A quick example to showcase how events work:

# This example requires the 'message_content' intent. import discord class MyClient(discord.Client): async def on_ready(self): print(f'Logged on as self.user>!') async def on_message(self, message): print(f'Message from message.author>: message.content>') intents = discord.Intents.default() intents.message_content = True client = MyClient(intents=intents) client.run('my token goes here') 

discord.py 2.3.2

A modern, easy to use, feature-rich, and async ready API wrapper for Discord written in Python.

Key Features

  • Modern Pythonic API using async and await .
  • Proper rate limit handling.
  • Optimised in both speed and memory.

Installing

Python 3.8 or higher is required

To install the library without full voice support, you can just run the following command:

 python3 -m pip install -U discord.py py -3 -m pip install -U discord.py

Otherwise to get voice support you should run the following command:

 python3 -m pip install -U  py -3 -m pip install -U discord.pyTo install the development version, do the following:

$ git clone https://github.com/Rapptz/discord.py discord.py python3 -m pip install -U .

Optional Packages

  • PyNaCl (for voice support)

Please note that when installing voice support on Linux, you must install the following packages via your favourite package manager (e.g. apt , dnf , etc) before running the above commands:

  • libffi-dev (or libffi-devel on some systems)
  • python-dev (e.g. python3.8-dev for Python 3.8)

Quick Example

Bot Example

You can find more examples in the examples directory.

Links

  • Documentation
  • Official Discord Server
  • Discord API

Создаём Discord-бота на Python

Сегодня мы напишем Discord-бота с помощью Python и discord.py. А также посмотрим на примеры ботов.

Всем привет, сегодня мы напишем Discord-бота на Python и discord.py + бонусом посмотрим на примеры ботов. Приступим ?

Перед работой

Перед тем, как начать, вам нужны:

  1. Python 3;
  2. discord.py;
  3. Discord-аккаунт и свой сервер.

Для установки discord.py воспользуйтесь пакетным менеджером:

pip3 install discord.py 

Создаём нашего бота

Перейдите на Developer Portal и нажмите на New application.

Создаём Discord-бота на Python 1

Вы создали своё приложение, на странице приложение перейдите в Bot >> Add Bot и создайте своего Discord-бота.

Сохраните токен бота! Дальше он нам понадобится!

Создаём Discord-бота на Python 2

Если всё прошло успешно, поздравляю, половина дела сделана ?

Добавление бота на сервер

Теперь можно добавить бота на сервер.

Перейдите в OAuth2 >> URL Generator, в Scopes выбираем Bot и ниже — права бота, копируем сгенерированный URL. Вставляем в браузер, и добавляем на наш сервер.

Создаём Discord-бота на Python 3

Эхо-бот

Напишем традиционного эхо-бота, и разберём каждую строчку кода.

import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': 'prefix', >bot = commands.Bot(command_prefix=config['prefix']) @bot.event async def on_message(ctx): if ctx.author != bot.user: await ctx.reply(ctx.content) bot.run(config['token']) 

Создаём Discord-бота на Python 4

import discord from discord.ext import commands 

Нужные нам импорты.

config =

Вспомогательный словарь config в котором храним токен и префикс команд (далее расскажу зачем нужен префикс команд).

bot = commands.Bot(command_prefix=config['prefix']) 

Создаём нашего бота, в аргументе передаём префикс.

@bot.event 

Декоратор, предназначенный для обработки событий, подробнее здесь.

async def on_message(ctx): 

Создаём асинхронную функцию, с параметром ctx, представляет из себя сообщение.

if ctx.author != bot.user: 

Проверка, не является ли автор сообщения нашим Discord-ботом. Дело в том, что если бот отправит сообщение, это будет новым событием, и тогда получается цикл.

await ctx.reply(ctx.content) 

Отвечаем на сообщение (ctx.reply), в аргументы передаём сообщение (ctx.content).

bot.run(config['token']) 

Запускаем нашего бота, в аргументы передаём токен бота.

Надеюсь вы разобрались с кодом, и мы можем переходить далее.

Обработка команд

Перед тем, как обрабатывать команды, нам пригодится наш префикс.

import random import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': '$', >bot = commands.Bot(command_prefix=config['prefix']) @bot.command() async def rand(ctx, *arg): await ctx.reply(random.randint(0, 100)) bot.run(config['token']) 

Создаём Discord-бота на Python 5

@bot.command() 

Декоратор обработки команд

async def rand(ctx, *arg): 

Асинхронная функция rand

await ctx.reply(random.randint(0, 100)) 

Отвечаем на сообщение, в аргументы передаём случайное число от 0 до 100

Бонус

import random import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': '$', >bot = commands.Bot(command_prefix=config['prefix']) @bot.command() @commands.has_role("Хозяин") async def rand(ctx, *arg): await ctx.reply(random.randint(0, 100)) bot.run(config['token']) 
import discord from discord.ext import commands config = < 'token': 'your-token', 'prefix': '$', >bot = commands.Bot(command_prefix=config['prefix']) @bot.command() async def kick(ctx, user : discord.User(), *arg, reason='Причина не указана'): await bot.kick(user) await ctx.send('Пользователь был изгнан по причине ""') bot.run(config['token']) 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *