1
1
1 22020-07-28 12:43:22
Python
1 2, 2020-07-28 12:43:22

Discord.py how to make a global chat?

I wanted to make a global chat in a bot using discord.py.

Its principle of operation: if a person wrote a message in this chat, then the bot deletes it and writes (to all servers where there is a bot in the specified channel) the person's nickname and his message.
The problem is that the bot only sends a message to the server where it was written, but does not broadcast to all servers.

Here is my code:

globals_chat = 'глобальный-чат'

@client.event
async def on_message( message ):
  channel = discord.utils.get( message.guild.text_channels, name = globals_chat )
  if message.author.id == айди бота:
    pass
  else:
    if message.channel == channel:
      for a in client.guilds:
        if channel in a.text_channels:
          await message.delete()
          await channel.send( '**{0.author}:** {0.content}'.format( message ) )

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Nevzorov, 2020-07-28
@weRifiCatoR

Through discord.utils.getyou get the channel of the server in which the message was written.
It belongs to the server where the message is written. A channel object with the same name will be different on other servers.
Therefore: you need to look for the channel on the server to which the message is sent

GLOBAL_CHAT = 'глобальный-чат'  # PEP8: Названия констант пишутся капсом

@client.event
async def on_message(message):
    channel = discord.utils.get(message.guild.text_channels, name=GLOBAL_CHAT)
    if message.author.id == client.user.id:
        return  # return предотвратит выполнение следующего кода
    if message.channel.id != channel.id:
        return
    await message.delete()  # удаляем сообщение один раз
    for guild in client.guilds:
        if channel := discord.utils.get(guild.text_channels, name=GLOBAL_CHAT):
            # py3.8: walrus operator ("моржовый" оператор)
            # равносильно следующему:
            # channel = discord.utils.get(guild.text_channels, name=GLOBAL_CHAT)
            # if channel: ...
            try:
                await channel.send('**{0.author}:** {0.content}'.format(message))
            except discord.Forbidden:
                print(f"Невозможно отправить сообщение на сервер {guild.name}: Недостаточно прав")
            except discord.HTTPException as e:
                print(f"Невозможно отправить сообщение на сервер {guild.name}: {e}")

C
CRAIZES YT, 2021-11-12
@maximnaum

by the way, if you need with the name of the server, then keep:

GLOBAL_CHAT = 'глобальный-чат'  # PEP8: Названия констант пишутся капсом

@client.event
async def on_message(message):
    channel = discord.utils.get(message.guild.text_channels, name=GLOBAL_CHAT)
    if message.author.id == client.user.id:
        return  # return предотвратит выполнение следующего кода
    if message.channel.id != channel.id:
        return
    await message.delete()  # удаляем сообщение один раз
    for guild in client.guilds:
        if channel := discord.utils.get(guild.text_channels, name=GLOBAL_CHAT):
            # py3.8: walrus operator ("моржовый" оператор)
            # равносильно следующему:
            # channel = discord.utils.get(guild.text_channels, name=GLOBAL_CHAT)
            # if channel: ...
            try:
                await channel.send('**[{0.guild}]** **{0.author}:** {0.content}'.format(message))
            except discord.Forbidden:
                print(f"Невозможно отправить сообщение на сервер {guild.name}: Недостаточно прав")
            except discord.HTTPException as e:
                print(f"Невозможно отправить сообщение на сервер {guild.name}: {e}")

if you have any questions, you can write to me in ds: CRAIZESdsYT#0953 :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question