Entering data into a variable and outputting it in a module Discord.py

I just recently started working with a module for Python 'Discord.py' and I had the need to create a function that works like this: the user enters text, and the bot re-sends this text. Please help me figure out how to do this. Here is my code:

import discord
from discord.ext import commands

bot = discord.ext.commands.Bot(command_prefix = "!");

client = discord.Client()

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('!привет'):
        await message.channel.send(f' { message.author.mention }, Привет!')

    if message.content.startswith('!хелп'):
        await message.channel.send('Я бот, да ты и сам знаешь.\n**Мои команды:**\n```!привет - Вывод сообщения с приветом.``` ```!хелп - эта команда.```')

    if message.content.startswith('!print '): #После команды !print пользователь должен ввести текст который как-то нужно указать, возможно в переменной.
        await message.channel.send('') #Бот его должен вывести.

client.run('TOKEN')

My Python 3.7.0

Author: strawdog, 2020-11-30

1 answers

There are 2 types of bots - discord.Client() and commands.Bot()

In the code, you declare both, but use only the first one - client:

bot= discord.ext.commands.Bot(command_prefix = "!")

client= discord.Client()

The bot object differs in that it can process incoming commands together with individual arguments. Such commands are declared by the string @bot.command(), which is placed before the asynchronous function of the command. The client object cannot process such a command. But bot, can catch in addition to the command also events marked as @bot.event. These events include: on_ready() - called when the bot is loaded and ready to work, on_message() - called when the bot receives any message, etc.

You have in your code just the same processing of receiving the message on_message(), in which you try to simulate the execution of commands by comparing the incoming words. This is wrong. In any case, this is not what you need. If you want to process commands, with the transmission of various commands in them if there are no arguments, then you need to use the commands.Bot() object that you declared in the code under the name bot. Next to it.


When defining an object, you specify the parameter command_prefix in parentheses, which is equal to the value "!". The "prefix" parameter is mandatory and is needed so that when using it, the bot determines that the command was used in the chat. The command itself looks like this:

@bot.command() # указываем боту на то, что это его команда
async def command(ctx, *, text):
    await ctx.send(f'Получен текст: {text}')

The command is called when writing such a construction in the chat: [префикс][имя команды] [аргументы]

To call this command, you need to write to the chat "! command text to be returned", to which the bot will respond: "Text received: text to return"

Here command is the name of the command; the argument ctx is the context, the required argument, roughly speaking, is the text channel in which the command was called. The text argument will contain all the text after "! command " . The asterisk is needed in order for the bot to get in as an argument, the entire text after the space, not just the first word. That is, if you, for example, need to get 2 numeric values separated by a space from the user, the argument processing will look like this: async def command(ctx, arg1: int, arg2: int)

From the context ctx , you can get the author's object - author = ctx.message.author and many other useful things. For more information about working with arguments, be sure to read the documentation!


As for your code; First of all, I suggest completely remove the discord.Client object from it, replacing it with commands.Bot. To avoid rewriting the entire code, just change bot to client in the line bot = discord.ext.commands.Bot(command_prefix = "!")

Then, we declare the full commands in the code and get the result:

import discord
from discord.ext import commands

client = discord.ext.commands.Bot(command_prefix = "!")

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.command()
async def привет(ctx):
    await ctx.send(f'{ctx.message.author.mention}, Привет!')

@client.command()
async def хелп(ctx):
    await ctx.send('Я бот, да ты и сам знаешь.\n**Мои команды:**\n```!привет - Вывод сообщения с приветом.``` ```!хелп - эта команда.```')

@client.command()
async def print(ctx, *, text):
    await ctx.send(f'{text}')   

client.run('TOKEN')

And in the on_message() construct, you need to process exactly those messages that are not a command and do not need arguments to process them. For example, through this event, you can catch a checkmate, after which the bot will issue a warning to the participant. Good luck:)

 0
Author: denisnumb, 2020-12-01 04:23:16