T
T
Tim Novikov2021-08-13 23:07:29
Python
Tim Novikov, 2021-08-13 23:07:29

How to say something on behalf of a bot in Discord?

Prefix - "!"
async def say( ctx, arg ):
await ctx.send(arg)
Here is an example function.
1) If we write "!say Text1 Text2" to the chat, the bot will write only "Text1" how to make the argument enter the sentence in full and not just the word before the first space.
2) I want to write on behalf of the bot;
there is a private text channel "admin" in which I send "!say "CHANNEL NAME"Text1, Text2"
In turn, the bot sends a message "Text1, Text2" to the channel called "CHANNEL NAME"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Endora Blackwell, 2021-08-14
@Tim_1527

The channel_conv function looks for a channel in the first word, if it does not find it, it sends None, which creates an exception when trying to send, resulting in sending to the current channel
ctx, *, text - an asterisk means that everything after ctx will be written to text
split - splits the string to the isdigit list
- check if the string is a number
replace - replaces the fragment in the string with another given one (In this case, the channel is replaced with an empty space so that if it is sent to another channel, it will not be sent along with the text)

async def say(ctx, *, text):
    def channel_conv(text):
        value  = text.split(" ")
        string = value[0]

        if string.isdigit():
            return (
                client.get_channel(int(string)),
                text.replace(string, "")
            )
        elif string.startswith("<#"):
            return (
                client.get_channel(int(string[2:20])),
                text.replace(string, "")
            )
        else:
            return (
                None,
                text
            )

    try:
        channel = channel_conv(text)
        await channel[0].send(channel[1])
    except:
        await ctx.send(text)

You can also use the converter from the original library:
from discord.ext.commands import TextChannelConverter

The code:
async def say(ctx, *, text):
    v = text.split(" ")

    try:
        channel = await TextChannelConverter().convert(ctx = ctx, argument = v[0])
        await channel.send(text.replace(v[0], ""))
    except:
        await ctx.send(text)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question