#🔒 I cant put my discord bot to reply my messages

55 messages · Page 1 of 1 (latest)

idle spruce
#

He only says: I cant send an empty message.
But message inst empty

errant nightBOT
#

@idle spruce

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

molten iris
#

send your code

idle spruce
#

he is the code:

    async def on_message(self, message):
        if message.author == self.user:
            return  
        
        # Verifica se a mensagem é do canal de origem e do servidor de origem
        if message.channel.id == id_canal_origem and message.guild.id == id_servidor_origem:
            # Obtém o canal de destino no servidor de destino
            canal_destino = self.get_channel(id_canal_destino)
            if canal_destino:

                await canal_destino.send(f"{message.content}")
#

@molten iris

molten iris
#

and your full error please

plush haven
#

the message content will be empty if the message content intent is not enabled

idle spruce
molten iris
#

!intents

errant nightBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

plush haven
#

yeah exactly like the example

idle spruce
molten iris
#

intents.message_content = True

idle spruce
#

i put, but stay empty

plush haven
#

where did yohu put it

#

if it's inside the client object try self.intents.messsage_content = True

idle spruce
#

in start

#

here

#

@plush haven

plush haven
#

thats doing something different to your client definition

#

can you send your full code

idle spruce
# plush haven can you send your full code
import discord
from discord import app_commands
from discord.embeds import Embed
import asyncio
from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

id_do_servidor = (974843731528253450)  # id
id_servidor_origem = (974843731528253450)
id_canal_origem = (974843731528253454)
id_servidor_destino = (1129386335719923852)
id_canal_destino = (1129386336420368409)

class client(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            try:
                await tree.sync(guild=discord.Object(id=id_do_servidor))
                self.synced = True
            except Exception as e:
                print(f"Erro ao sincronizar comandos: {e}")
        print(f"O {self.user} foi iniciado.")

    async def on_message(self, message):
        if message.author == self.user:
            return
        
        
        if message.channel.id == id_canal_origem and message.guild.id == id_servidor_origem:
            
            canal_destino = self.get_channel(id_canal_destino)
            if canal_destino:
                
                await canal_destino.send(f"{message.content}")

aclient = client()
tree = app_commands.CommandTree(aclient)```
#

here

plush haven
#

ok what are you actually trying to do

idle spruce
#

send a message in another discord

plush haven
#

ok

idle spruce
#

copy message in original discord and send in secundary discord

plush haven
#
import discord
from discord import app_commands
from discord.embeds import Embed
import asyncio
from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

id_do_servidor = 974843731528253450  # id
id_servidor_origem = 974843731528253450
id_canal_origem = 974843731528253454
id_servidor_destino = 1129386335719923852
id_canal_destino = 1129386336420368409

@bot.event
async def on_message(self, message):
    if message.author == self.user:
        return
      
      
    if message.channel.id == id_canal_origem and message.guild.id == id_servidor_origem:
        canal_destino = self.get_channel(id_canal_destino)
            if canal_destino:
                await canal_destino.send(f"{message.content}")

@bot.command()
async def sync(ctx):
    await ctx.send("starting CommandTree Sync")
    await bot.tree.sync(guild=discord.Object(id=id_do_servidor))
    await ctx.send("sync complete")

bot.run(TOKEN)```
idle spruce
#

i need async def on_ready(self):

#

in this code dont ahve

#

have

plush haven
#

you should never sync in on ready

#

Just make it a text command

#

from the discord.py discord:

Don't change_presence (or make API calls) in on_ready within your Bot or Client.
Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.

Instead set the activity and status kwargs in the constructor of these Classes.

bot = commands.Bot(command_prefix="!", activity=..., status=...)

As noted in the docs, on_ready is also triggered multiple times, not just once.

Basically: don't 👏 do 👏 shit 👏 in 👏 on_ready.

idle spruce
#

ok, one moment

#

i got @plush haven

#

but

#

still empty message

#
class client(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        self.intents.message_content = True
        self.synced = False
idle spruce
#

@plush haven
If I delete that part of the code, it will break everything else, understand?

plush haven
#

What are the other parts of your code

idle spruce
#
def chroma_key_replace(image_path, target_color, threshold=100, range_threshold=50):
    foreground = Image.open(image_path)

    width, height = foreground.size
    pixel_data = foreground.load()

    for y in range(height):
        for x in range(width):
            current_color = pixel_data[x, y]
            color_distance = sum((abs(a - b) for a, b in zip(current_color, target_color)))

            if color_distance < threshold and all(abs(a - b) < range_threshold for a, b in zip(current_color, target_color)):
                pixel_data[x, y] = (0, 0, 0, 0)  # Define os pixels correspondentes como transparentes

    return foreground

@tree.command(guild=discord.Object(id=id_do_servidor), name='criar-perfil', description='Use para criar um perfil no WorkedIn.')
async def informacoes(interaction: discord.Interaction, nome: str, idade: int, ocupacao: str, pais: str, disponibilidade: str, historico: str, profissoes_interesse: str, qualidades: str, data_imigracao: str, complementos: str, foto: str, canal_destino: discord.TextChannel):

    response_foreground = requests.get(foto)
    if response_foreground.status_code == 200:
        image_data = BytesIO(response_foreground.content)

        foreground = chroma_key_replace(image_data, (126, 202, 25),
                                         range_threshold=150)
        
        desired_width = 3200
        
        aspect_ratio = foreground.width / foreground.height
        desired_height = int(desired_width / aspect_ratio)
        
        foreground = foreground.resize((desired_width, desired_height), Image.LANCZOS)
        
        result_image = Image.open("background.png")
        
        overlay_position = ((result_image.width - foreground.width) // 2, result_image.height - foreground.height)
        result_image.paste(foreground, overlay_position, foreground)
        
        result_image_path = "imagens/chroma_key_with_overlay.png"
        result_image.save(result_image_path)

        
        image_file = discord.File(result_image_path, filename="chroma_key_with_overlay.png")

        embed = Embed(
            title=nome,
            description=f"**Idade:** {idade}.\n**Ocupação:** {ocupacao}.\n**País de origem:** {pais}.\n**Disponibilidade:** {disponibilidade}.\n**Histórico profissional:** {historico}.\n**Profissões de interesse:** {profissoes_interesse}.\n**Qualidades/Qualificações:** {qualidades}.\n**Data de imigração ao País (Matrix):** {data_imigracao}.\n\n**Complementos:**\n{complementos}.",
            color=1337006
        )
       

Have more, but i got the max characters

#

@plush haven

plush haven
#

!paste

errant nightBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

idle spruce
# plush haven !paste

This part doesn't matter much, but I can't change that part because of the rest of the code, isn't there a way to make it copy the messages like that?

plush haven
#
import discord
from discord import app_commands
from discord.embeds import Embed
import asyncio
from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

id_do_servidor = (974843731528253450)  # id
id_servidor_origem = (974843731528253450)
id_canal_origem = (974843731528253454)
id_servidor_destino = (1129386335719923852)
id_canal_destino = (1129386336420368409)

class client(discord.Client):
    def __init__(self):
        super().__init__(intents=discord.Intents.default(message_content=True, members=True))
        self.synced = False

    async def on_ready(self):
        await self.wait_until_ready()
        if not self.synced:
            try:
                await tree.sync(guild=discord.Object(id=id_do_servidor))
                self.synced = True
            except Exception as e:
                print(f"Erro ao sincronizar comandos: {e}")
        print(f"O {self.user} foi iniciado.")

    async def on_message(self, message):
        if message.author == self.user:
            return
        
        
        if message.channel.id == id_canal_origem and message.guild.id == id_servidor_origem:
            
            canal_destino = self.get_channel(id_canal_destino)
            if canal_destino:
                
                await canal_destino.send(f"{message.content}")

aclient = client()
tree = app_commands.CommandTree(aclient)```
errant nightBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.