#discord-bots

1 messages · Page 347 of 1

leaden olive
#

is there anyway to check what permissions the bot needs so i dont have to check administration

shrewd apex
shadow vigil
#

!rule 5 it seems like you are creating a self bot as the headers aren't correct

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

dense arch
#

PS C:\Users\newca\Desktop\HavenCore> & c:/Users/newca/Desktop/HavenCore/.venv/Scripts/python.exe c:/Users/newca/Desktop/HavenCore/main.py
& : The term 'c:/Users/newca/Desktop/HavenCore/.venv/Scripts/python.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At line:1 char:3

  • & c:/Users/newca/Desktop/HavenCore/.venv/Scripts/python.exe c:/Users/ ...
  • + CategoryInfo          : ObjectNotFound: (c:/Users/newca/...ipts/python.exe:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
sick birch
#

also you can just do py main.py

shrewd timber
#

which software should i use to do python?

opaque acorn
#

File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 544, in connect
proto = await self._create_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 911, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 1235, in _create_direct_connection
raise last_exc
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 1204, in _create_direct_connection
transp, proto = await self._wrap_create_connection(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/aiohttp/connector.py", line 994, in _wrap_create_connection
raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

#

what do i do

abstract fox
#

how to make an option optional in a / command

naive briar
#

Give the argument a default value

abstract fox
abstract fox
#

ty

naive briar
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

10
abstract fox
abstract fox
#

yep

#
@bot.tree.command(name="deploy", description="We're going on a deployment!")
@app_commands.describe(host="How long? Give me a date in which it will end please. [DD/MM/YYYY]", co_host="Why do you need this?", start_time="", overseer="")
async def deploy(interaction: discord.Interaction, host: str, co_host: str, start_time : Optional[str], overseer : Optional[str],) -> None:```
import is long before this but
#

that's my code ignore if it looks a bit odd, it's borrowed from another one of my commands

abstract fox
zenith yarrow
#

What is the error tho

abstract fox
#

nvm i think i fixed it

abstract fox
#

yeah it's called add dyno and then ?kick ?ban ?unban 💀

naive briar
#

Discord's UI has them all

toxic breach
#

Hello, is anyone else having problem with installing discord components?

plush nest
#

Hello which VPS you guys suggest?
Want to run Python 3.10 code 7-24 continously,
my issue not discord bot related but kinda same, working with API's Trading stuff

naive briar
#

The popular ones, anyway

toxic breach
naive briar
#

What library are you using?

toxic breach
#

3.12.2

naive briar
#

No, I mean your Discord library, like discord.py or something

toxic breach
#

Oh sorry

naive briar
#

You can see the official examples here. Here's a basic one for beginners

toxic breach
#

thanks broo

next garden
#

hello bot developrs
can yall check whether your discord application ID and your bot's public ID are the same or not

#

to check your discord application ID, go to discord.dev > application > general info > application ID

#

asking this cuz im not sure whether making my discord application ID public would be a good idea or not

cloud dawn
#

You'd need atleast the client secret too to actually cause any harm.

next garden
#

and does discord have any official writing on this? i couldnt find 1 myself

cloud dawn
#

It wouldn't matter much since like I said above you'd need both the ID and the client secret.

slate swan
#

I cant add a discord users thumbnail to an embed
Error:

                    ^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'```
My Code:
    thumbnail_url = member.avatar_url if member.avatar else discord.Embed.Empty

    embed = discord.Embed(
        title='User Joined',
        description=f'{member.mention} has joined the server.',
        color=discord.Color.green()
    )
    embed.set_thumbnail(url=thumbnail_url)```
slate swan
#

how do i add slash commands to my bot?

vestal acorn
naive briar
thorn beacon
#

Can someone help me start and explain how to make a discord bot?

slate swan
thorn beacon
#

Send some.

#

I can’t find any.

slate swan
#

what are you coding

#

what language

thorn beacon
slate swan
thorn beacon
#

Alr.

toxic breach
#

I am trying to do an anti fake account system

#

My Error: in on_member_join delta = (now - created).days ~~~~^~~~~~~~~ TypeError: can't subtract offset-naive and offset-aware datetimes

#

Code: ```py
@bot.event
async def on_member_join(member):
created = member.created_at
now = datetime.now()
delta = (now - created).days
if delta < 30:
antialtlogs = bot.get_channel(1221086723132358697)
alt = discord.Embed(timestamp=datetime.utcnow(), title=":name_badge: Ενα καινουργιος λογαργιασμος προσπαθησε να μπει στον The Society :name_badge:", colour = discord.Colour.red())
alt.add_field(name=":capital_abcd:User's name:", value=f"{member.name}")
alt.add_field(name=":watch:Creation date:", value=f"{member.created_at.strftime('%d %B %Y')}")
alt.add_field(name=":label:User's Account:", value=f"{member.mention}")
await antialtlogs.send(embed=alt)

#

Does somebody know how to fix it?

slate swan
#

datetime.now(timezone.utc)

Unrelated to discord bots btw

toxic breach
#

Yeah that worked

#

Thx bro

dense arch
#

Can someone help?

#

how do i fix that??

slate swan
leaden olive
#

whats that

slate swan
#

Stop spamming Discord's API, wait a few hours and fix whatever is spamming the API during that time

#

And that way of hiding the token is trash, better reset your token now

spice widget
#
def send_embed_to_webhook(user_id, badge_id, badge_name):
    embed = {
        "title": RobloxAPIs.RobloxGetUsername(user_id),
        "url": f"https://www.roblox.com/badges/{badge_id}/badge",
        "description": f"{RobloxAPIs.RobloxGetUsername(user_id)} has earned the badge: {badge_name}",
        "color": 0x00b0f4,
        "timestamp": datetime.datetime.now(datetime.timezone.utc).isoformat(),
        "image": {
            "url": RobloxAPIs.RobloxGetBadgeImage(badge_id)
        },
        "thumbnail": {
            "url": RobloxAPIs.RobloxGetUserProfileImage(user_id)
        }
    }

    payload = {
        "content": "||<@&1220868554669424651>||",
        "embeds": [embed]
    }

    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.post(webhook_url, json=payload, headers=headers)
    print(f"Webhook status code: {response.status_code}")
    if response.status_code != 204:
        print(f"Failed to send embed for user {user_id}. Status code:", response.status_code)

I'm trying to trigger a webhook when something changes on another website. Printing the data works fine, but when attempting to send the webhook, it doesn't go through, despite receiving a 204 status code any help would be appreciated

mossy jacinth
#

Why does my bot sometimes say The application did not respond and then throw an error with 404 Not Found?
It happens to all commands sometimes for no reason at all.

Traceback (most recent call last):
  File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\application_command.py", line 918, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Users\blaul\Desktop\admin helper\main.py", line 631, in help
    await ctx.send(embed=embed)
  File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\interactions.py", line 540, in send
    return await self.response.send_message(
  File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\interactions.py", line 896, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\webhook\async_.py", line 195, in request
    raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

The above exception was the direct cause of the following exception:

nextcord.errors.ApplicationInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction

If you try to use the command again it works like it should but sometimes it just throws that error so is there some way to fix that?

golden portal
naive briar
spice widget
golden portal
#

🤔

tepid dagger
slate swan
#

how you want to call emoji

#

what does that mean

tepid dagger
#

i phrased that wrong

#

how do you use a custom emoji in message.add_reaction

slate swan
#

so you need id of an emoji

#

then you use bot.get_emoji(id)

#

and what it returns, you pass it to .add_reaction()

tepid dagger
#

so like

emoji = client.get_emoji(id)
message.add_reaction(emoji)
#

?

slate swan
#

yeah

#

but

#

i belive .add_reaction is a coro

#

so you need to await it

tepid dagger
#

wait how do you get an emoji id

slate swan
#

you put \ before emoji in discord chat

#

then it outputs something like this !this

#

and the 470903994118832130 is the id

keen sorrel
#

This is a python script of a Discord Bot I developed for my users, basically I am working on a Automation project on discord my ultimate goal is to develop discord bot which helps my client to perform auto operations like Auto Posting/Auto Comment ... without getting banned or suspend by discord , Insha-Allah soon this project will be completed I want your feed back guys related to this short video about code. Thanks

leaden olive
#

whats the permission called to remove the perms of someone using the everyone ping ?

slate swan
#

!d discord.Permissions.mention_everyone

unkempt canyonBOT
leaden olive
#

thanks!

zenith yarrow
#

How to get message id from message link ?

slate swan
#

this is the message link

#

267624335836053506 343944376055103488 1221412309164097626

those numbers are as follows:
guild id
channel id
message id

formal basin
#

how to get the author of a person that created a channel?

#

from on_guild_channel_create event

#

!d discord.on_guild_channel_create

unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild).

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
formal basin
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
slate swan
#

!d discord.Message.guild

unkempt canyonBOT
formal basin
#

how to get the author of a person that created a channel?
from on_guild_channel_create event

slate swan
slate swan
slate swan
#

fetch the message and check the .guild property

#

most likely you will get Forbidden error cause bot will not be in the guild, then you know its not the guild you want

#

like i said, you check .guild property if it fetches

#

you can either hardcode the guild id you want it to be or check it from context

#

!d discord.Message.guild

unkempt canyonBOT
naive briar
#
if something.guild is not None:
    # do something :P

(probably)

formal basin
formal basin
#

so it is in many6 servers

#

i cant put an id

slate swan
#

!d discord.Guild.owner_id

unkempt canyonBOT
slate swan
#

you wanna fetch by message_id not channel_id i belive thats just bad variable name

formal basin
slate swan
#

if only you were to check the guide i linked

naive briar
#

Look around the sections

formal basin
slate swan
#

well you got channel out of nowhere

naive briar
#

What could it be? 😼

slate swan
#

just use bot.fetch_message

#

are you using client😐

#

well then use guild

#

ctx.guild

slate swan
#

show code

pale zenith
#

you need to get a channel

slate swan
pale zenith
slate swan
#

yea

#

well if you are checking by channel

#

yes

hushed galleon
unkempt canyonBOT
#

discord/message.py lines 1900 to 1905

@utils.cached_slot_property('_cs_channel_mentions')
def channel_mentions(self) -> List[Union[GuildChannel, Thread]]:
    if self.guild is None:
        return []
    it = filter(None, map(self.guild._resolve_channel, self.raw_channel_mentions))
    return utils._unique(it)```
quick gust
#

in what cases can guild.owner return None?

hushed galleon
unkempt canyonBOT
#

discord/guild.py lines 995 to 998

@property
def owner(self) -> Optional[Member]:
    """Optional[:class:`​Member`​]: The member that owns the guild."""
    return self.get_member(self.owner_id)  # type: ignore```
quick gust
#

ah, well its returning None everytime 😔

hushed galleon
#

do you have Intents.members enabled? that's needed for dpy to automatically cache members

quick gust
#

sadly no, I am not verified for it

#

any work around?

hushed galleon
#

i guess just fetch the member then

#

!d discord.Guild.fetch_member

unkempt canyonBOT
#

await fetch_member(member_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) from a guild ID, and a member ID.

Note

This method is an API call. If you have [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) and member cache enabled, consider [`get_member()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.get_member) instead.

Changed in version 2.0: `member_id` parameter is now positional-only.
quick gust
#

I've already requested once but they said "the feature isnt innovative enough"

quick gust
# unkempt canyon

and how do I get the ID of the guild owner since guild.owner is returning None

hushed galleon
unkempt canyonBOT
quick gust
#

ah yeah

#

thanku

hushed galleon
#

lol it just says "use guild.owner instead"

quick gust
#

💀 little do they know

quick gust
#

let me see

hushed galleon
#

owner_id is always available since its part of the guild payload

quick gust
#

oh gotcha

hushed galleon
#

i wonder why dpy doesnt yet have try_* or getch_* methods, maybe its to reduce library bloat?

quick gust
#

I'm using disnake which does have only getch_user

hushed galleon
#

ah cool

#

i guess its not that hard to write your own helper functions to do the same thing, e.g. py async def try_member(guild: discord.Guild, id: int) -> discord.Member | None: return guild.get_member(id) or await guild.fetch_member(id)

quick gust
#

that is true

slate swan
hushed galleon
#

o derp ye

naive briar
#

Is it your intention to try to delete the message every loop?

quick gust
slate swan
quick gust
#

ah ok

turbid condor
#

None type

hushed galleon
#

oh wait, you're trying to detect channel mentions that for the same guild?

#

in that case yeah you'll probably want to manually get the channel

#

!d discord.Message.raw_channel_mentions does the same regex stuff btw

unkempt canyonBOT
hushed galleon
#

i think you'll also want to consider matching channel links in the format https://discord.com/channels/GUILD_ID/CHANNEL_ID[/MESSAGE_ID] or similar

#

yeah you should check for both

thin raft
#
if any(channel_id not in message.guild.channels for channel_id in message.channel_mentions):
  await message.delete()
#

smt like that id say

hushed galleon
#

yeah something like that, except with raw_channel_mentions so you get the channel IDs that dont exist in the guild

thin raft
#

wdym by that

#

channel_mentions doesnt return external channels?

#

!d discord.Message.channel_mentions

unkempt canyonBOT
hushed galleon
thin raft
#

please read

#

don't copy paste every code you see

#
if any(guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):
  await message.delete()
#

or

#

yeah that would be it

#

cant think of a better way

hushed galleon
thin raft
hushed galleon
#

well, you need to define the guild variable

thin raft
#

or replace it with message.guild

hushed galleon
#

whats the regex to catch the various subdomains discord uses?

thin raft
#

doesnt redirect to nowhere

#

canary maybe?

#

not to be an asshole, but that's quite a simple python task to be fair

#

they already have a lot of mod tools, you're just asking something too specific

#

automod

#

you can somewhat delete adverts

#

but if you want extra mod tools, then code it yourself

#

it's a free platform that doesn't charge you, you really can't complain

#

if they had to implement every user edge case they would run out of money in less than a day

naive briar
#

Discord moment

wicked herald
#

anyone created slack bots before?

naive briar
#

This is a Discord bot channel. But probably

thin raft
slate swan
#

Though not here

young dagger
pseudo saffron
#
import config
import discord
from discord.ext import commands
from discord import app_commands
import math

app = commands.Bot(command_prefix=".", intents= discord.Intents.all())

@app.event
async def on_ready():
    print("hi")
    try:
        synced = await app.tree.sync()
        print(f"sync{len(synced)} command")
    except Exception as e:
        print(e)

@app_commands.command(name="taschenrechnen", description="taschenrechner1")
@app_commands.choices(choices=[
    app_commands.Choice(name="+", value="+"),
    app_commands.Choice(name="-", value="-")
])

async def taschenrechner( i: discord.Interaction,zahl1: int, choices:app_commands.Choice[str],zahl2: int):
    if choices.value == "+":
        await i.response.send_message(zahl1 + zahl2)
    elif choices.value == "-":
        await i.response.send_message(zahl1 - zahl2)







app.run(config.token)``` 
why it dont sync my command
#

i have application commands on and all that

golden portal
#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
slate swan
#

How do I call a command within a command using app_commands and cogs? I dont see 'invoke' as an option, I only see if for discord.ext.commands.Bot.invoke. In the discord api I do read there is a discord.app_commands.CommandInvokeError but for some reason not a discord.app_commands.Invoke .The sudo code I made is below. It prints out the print(command.name) without an issue just need the last line.

    @app_commands.command(name = "test", description="Test")
    
    async def test(self, interaction: discord.Interaction) -> None:
        
        commands = self.get_app_commands()
        for command in commands:
            if command.name == 'roster':
                print(command.name)
                await self.invoke(command.name)
naive briar
#

I don't think bots can invoke app commands

hushed galleon
slate swan
#

just wondering if a command ive made is breach of TOS,

    @commands.command(name="nuke", description="Nukes the channel command was used in.")
    @has_permissions(manage_channels=True)
    @commands.cooldown(1, 30, commands.BucketType.guild)
    async def nuke(self, ctx):
        newchannel = await ctx.channel.clone()
        await newchannel.edit(position=ctx.channel.position)
        await ctx.channel.delete()
        await newchannel.send(f"Channel nuked by `{ctx.author.name}`.")```
naive briar
#

If someone were to invite the bot to nuke their own server, I guess not 🥴

echo echo
#

Thumbnail Previously Showing, but within the last week disappeared with no code changes

Python Version: 3.8.10

Here is my Python code that previously was showing the Thumbnail with the rest of the embed fields, haven't made any code changes since the last time it was implemented in my discord bot.

set_headshot = f"https://aaa.com/headshots/aaa/latest/1040x760/{player_id}.png" # URL Redacted
print(set_headshot)

embed = discord.Embed(title=f"{player_name} - Season Stats ({season})", color=0x4286f4)
current_time = dt.now().strftime('%Y-%m-%d %H:%M:%S')
embed.set_thumbnail(url=set_headshot)
embed.set_footer(text=f"Made by Fire, the Lit Mage • Timestamp: {current_time}", icon_url="https://s3-us-west-2.amazonaws.com/sportshub2-uploads-prod/files/sites/556/2022/11/17094810/basketball-gif-6.gif")

for stat, value in relevant_stats.items():
    embed.add_field(name=stat, value=value, inline=True)

# Create a view with interactable buttons
view = discord.ui.View(timeout=None)

prizepick_button = discord.ui.Button(style=discord.ButtonStyle.green, label="PrizePick Bets", custom_id=f"{player_id}_ppbets_{re.sub(r' ','$$',player_name)}")
prizepick_button.callback = prizepick_click

view.add_item(prizepick_button)

processing_in_progress = False
await ctx.send(embed=embed, view=view)```
When I print the url of where the image is and I manually go there it loads the image I am expecting to see as the thumbnail that was previously there. My only assumption is that some new restriction was added into the discord.py package where if I have too many embed fields or something else it restricts the thumbnail coming through. Now when I open dev tools inside Discord it doesn't even show the Thumbnail content within the embed when searching for it. The total embed fields that I am adding into the embed is 22 fields.
zenith yarrow
#
import discord 
from discord.ext import commands
from discord import app_commands
import sqlite3

conn = sqlite3.connect('database.db')
c = conn.cursor()


class reactionrole(commands.Cog):

  def __init__(self, bot):
    self.bot = bot

  @app_commands.command()
  async def reactionroleadd(interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):

    await interaction.response.send_message("hi")

    c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
    conn.commit()
    conn.close()
naive briar
#

You forgot the self argument

zenith yarrow
#

Damm

formal basin
#

How can a make a error handler for this

async def is_owner(inter: discord.Interaction) -> bool:
    if inter.user.id == inter.guild.owner.id:
       return True
    else:
       await inter.response.send_message("You need to be the owner to use this command", ephemeral=True)
slate swan
#

When check returns False

#

CheckFailed error is raised

#

And you Can handle it as any other error in error handler

formal basin
#

It raises an AttributeError

slate swan
#

Show the error

formal basin
# slate swan CheckFailed error is raised
2024-03-25 07:39:57 ERROR    asyncio Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at /Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py:1087> exception=AttributeError("'NoneType' object has no attribute 'id'")>
Traceback (most recent call last):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1089, in wrapper
    await self._call(interaction)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 849, in _invoke_with_namespace
    if not await self._check_can_run(interaction):
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 987, in _check_can_run
    return await async_all(f(interaction) for f in predicates)
  File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/utils.py", line 705, in async_all
    elem = await elem
  File "/Users/zagzag/Library/Mobile Documents/com~apple~CloudDocs/zagzag/zagzag.py", line 460, in is_owner
    if inter.user.id == inter.guild.owner.id:
AttributeError: 'NoneType' object has no attribute 'id'
#

this raises if the user is not an owner

#

if it is the owner

#

it works

slate swan
#

Use owner_id instead

formal basin
#

guild.owner_id?

slate swan
#

Ye

formal basin
#

ok

rugged shadow
#

https://discord.com/balls lmao

autumn pewter
#
@client.event
async def on_member_join(member):
    channel = client.get_channel(welcome_channel)
    embed = discord.Embed(
        description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
        color=0x000000,
        timestamp=datetime.datetime.now(),
    )
    await channel.send(embed=embed)

how can i add it to also auto role? I tried

  role = discord.utils.get(member.guild.roles, name='Role Name')
    await member.add_roles(role

but it gives me an error

autumn pewter
# vestal acorn which error does it raise?
Traceback (most recent call last):
  File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\c0d3\Desktop\gam3-discord_bot\main.py", line 26, in on_member_join
    await member.add_roles(role)
  File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\member.py", line 1051, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
                                 ^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'```
vestal acorn
#
 role = discord.utils.get(member.guild.roles, name='Role Name')
    await member.add_roles(role)``` was it directly in your code like this?
autumn pewter
#
@client.event
async def on_member_join(member):
    channel = client.get_channel(welcome_channel)
    embed = discord.Embed(
        description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
        color=0x000000,
        timestamp=datetime.datetime.now(),
    )
    role = discord.utils.get(member.guild.roles, name='Member
')
    await member.add_roles(role)
    await channel.send(embed=embed)
vestal acorn
#

else, you can use something like: py role = member.guild.get_role(#roleid)

autumn pewter
#
Traceback (most recent call last):
  File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\c0d3\Desktop\gam3-discord_bot\main.py", line 26, in on_member_join
    await member.add_roles(role)
  File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\member.py", line 1051, in add_roles
    await req(guild_id, user_id, role.id, reason=reason)
  File "C:\Users\c0d3\Desktop\gam3-discord_bot\bot-venv\Lib\site-packages\discord\http.py", line 739, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
vestal acorn
#

ah

#

your bot doesn't have enough permissions

autumn pewter
#

its role has admin

naive briar
#

You cannot edit the roles of the members with higher role hierarchy

autumn pewter
#

so i need to add that perm?

naive briar
#

What permission?

autumn pewter
#

it now has administrator and manage roles

#

still displays the same error

naive briar
#

Maybe I wasn't clear

autumn pewter
#

how can i fix that?

#

idk shi about roles

naive briar
#

Just move one of the bot's role to a very high position

autumn pewter
#

ohhh

naive briar
#

Unless you're testing the bot on yourself as the guild owner or something

#

That probably won't work, though I didn't test anything roles related for a long time

autumn pewter
#

nono i have test alt

naive briar
#

Oh nice

autumn pewter
#

it worked now 🎉

#

thanks so much yall helped me again'

vale wing
naive briar
#

It was poorly phased 🥴

#

Per usual for me

unreal shuttle
#

can I monetize a discord bot?

#

I coded one back in 2020 & haven't touched Python ever since

lyric solar
unreal shuttle
vestal acorn
#

see some famous bots like mee6, draftbot or dyno can be monetized

sick birch
left dew
#

im trying to display a ticket count in the ticket name but it keeps saying that count is None even tho ive set its defualt value to 1 in the databse

#
        cur.execute(f"SELECT * FROM ticket_count")
        y = cur.fetchone()```
hot sparrow
#

client.get_user(494483880410349595) returning None, its my own userid

leaden olive
#

ticket closing button doesnt work, if i restart the bot it works once but on the next ticket i get that error

sick birch
#

.get_ methods are cache lookups so it'll return None if the cache isn't populated

hot sparrow
sick birch
#

can you show your code

shrewd apex
#

are u sure u don't have multiple instances of bot or some instances you are sourcing from other files or modules

#

might wanna check if the pool has been set in the first place

hot sparrow
# sick birch can you show your code
emb=discord.Embed(title=item_name, url=item_url, description=f"# {price}\nPosted: {time_posted}\nSeller: [{seller_name}]({seller_url})\nCondition: {condition}", color=0x00ff00)
# emb.set_author(name=client.get_user(494483880410349595).name, icon_url=client.get_user(494483880410349595).display_avatar)
emb.set_author(name="speckly")
emb.set_footer(text=catFact)
emb.set_image(url=item_img)
if interaction:
    await interaction.followup.send_message(catFact)
else:
    CHANNEL = client.get_channel(channel_id)
    await CHANNEL.send(embed=emb)
hot sparrow
viscid hornet
hot sparrow
viscid hornet
#

and please for the love of god do this instead of whatever i just had to read ```py
emb = discord.Embed(
title = ...,
description = ...,
...
)

viscid hornet
#

or is this a loop?

#

like show me the surrounding code

hot sparrow
viscid hornet
#
# this line
await ctx.send(embed = embed)

# is surrounded by
@bot.command(name = 'embed')
async def send_embed(ctx):
    embed = discord.Embed(
        description = "this is an embed",
        color = discord.Color.green()
    )
    await ctx.send(embed = embed)
    await asyncio.sleep(5)
    await ctx.send("Waited 5 seconds after sending the embed. :+1:")```
hot sparrow
#

i am outside so i only have this for now, the command is create_thread

viscid hornet
#

alr i'll take a look

hot sparrow
#

thanks

viscid hornet
#

lemme find it

hot sparrow
viscid hornet
#

but dont change anything yet

hot sparrow
#

worried things will break yeah

viscid hornet
#

it wont magically solve the problem

viscid hornet
hot sparrow
viscid hornet
#

ohhh

#

alright

hot sparrow
viscid hornet
hot sparrow
#

i tried using the same event loop with another async thread function, which is probably old practice, but it blocks all incoming commands, the messages do send fine

viscid hornet
#

ie. have you done something like this? py await interaction.response.defer() await interaction.response.send_message(...)

#

(they can be any .response.)

hot sparrow
#

ooh defer sounds useful actually but its not the issue i think, im mostly using channel.send()

viscid hornet
#

like where are you getting it from

#

because if you are going to use interactions you should probably just use .send_message

hot sparrow
viscid hornet
#

use interactions instead

#
await interaction.response.send_message(embed = emb)```
#

try that and let me know how it goes

viscid hornet
zenith yarrow
#

I know it's something related to commas where do I have put the comma

#

@viscid hornet sorry for ping :>

viscid hornet
#

hellooo

naive briar
#

I'm very confused about the variables

hot sparrow
#
    await interaction.followup.send(embed=emb)

raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
viscid hornet
#

show full traceback

hot sparrow
# viscid hornet show full traceback
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\Dell\OD\Documents\compooting\Kurokami\bot.py", line 42, in cb
    await query_cb(item_name, interaction)
  File "C:\Users\Dell\OD\Documents\compooting\Kurokami\bot.py", line 128, in query_cb
    await interaction.followup.send(embed=emb)
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1805, in send
    data = await adapter.execute_webhook(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 177, in request
    async with session.request(
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client.py", line 1141, in __aenter__
    self._resp = await self._coro
                 ^^^^^^^^^^^^^^^^
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client.py", line 467, in _request
    with timer:
  File "C:\Users\Dell\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\helpers.py", line 701, in __enter__
    raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task
viscid hornet
#

so this line is the error py await interaction.followup.send(embed=emb)

#

wait wtf

#

try .response.send_message(...)

#

instead

hot sparrow
viscid hornet
hot sparrow
#
while True:
            s = time.time()
            await query_cb(item_name, interaction)
            print(f"{threading.current_thread().name}, time taken: {time.time() - s}")
            await asyncio.sleep(delay)
#

until thread gets stopped

viscid hornet
#

that might be a good idea

hot sparrow
#

what does this help in

#

i need to constantly send results in a channel

viscid hornet
#

ohhhh

#

ok lemme take another look cuz i closed it and i cant find it 😭

viscid hornet
#

make a help thread there and list your issue

#

im sorry but i cant help 😭

#

sorry for wasting your time ❤️

hot sparrow
viscid hornet
#

I FORGOT ABOUT THAT

#

😭

#

second hand embarrassment off the charts rn

hot sparrow
#

no wonder discord doesnt like threading

#

they support their own ones smh

viscid hornet
#

i was literally writing tasks code as we were speaking

viscid hornet
sturdy fractal
#

this error

@commands.command(name="reload", hidden=True)
    async def reload(self, ctx, *, cog: str = None):
        """Reload a cog."""
        if cog is None:
            await ctx.send("Please specify a cog to reload or 'all' to reload all cogs.")
            return

        if cog.lower() == "all":
            for extension in self.client.extensions:
                try:
                    await self.client.reload_extension(extension)
                    await ctx.send(f"Cog `{extension}` reloaded successfully.")
                except commands.ExtensionError as e:
                    await ctx.send(f"Failed to reload cog `{extension}`: {e}")
        else:
            try:
                await self.client.reload_extension(cog)
                await ctx.send(f"Cog `{cog}` reloaded successfully.")
            except commands.ExtensionError as e:
                await ctx.send(f"Failed to reload cog `{cog}`: {e}")
naive briar
#

You need to have the extension already loaded before reloading it 🫠

sturdy fractal
sturdy fractal
#

i m using setup hook

#

to load them

naive briar
#

I don't think the error would lie to you

sturdy fractal
#

why do u think i m lieing to u

#
   async def setup_hook(self):
        for file in EXTENSIONS:
            await self.load_extension(file)
            print(file, "activated!")
#

here it is i loaded them

naive briar
#

I said the error, but alright

sturdy fractal
#
EXTENSIONS = [
    "cogs.events",
    "cogs.tools",
    "cogs.moderation",
    "cogs.owner",
    "cogs.fun",
    "cogs.General",
    "cogs.tech_news",
    "cogs.utility",
]
sturdy fractal
#

do they mean to be loaded again?

#

the more interesting thing is
i can use all thoes cmds in owner.py
and when i try to reload the cogs it says its not loaded

#

then how tf m i even using thoes all cmds?

#

@vapid parcel

quick gust
#

so

await self.client.reload_extension(f"cogs.{cog}")
#

or u can just do !!reload cogs.owner too

proven timber
#

i have install ffmpeg and path it but i still get this err here:https://srcb.in/EsAAHMCH90

File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\player.py", line 183, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.?[0m

sturdy fractal
sturdy fractal
#

idk how it was working back yesterday

toxic breach
#

Does anyone know how to make my bot send a message to a user when a message reaches 3 reactions?

quick gust
hot sparrow
# hot sparrow

i tried this and the messages send just fine now, but these looping tasks block commands, one of the tasks is this line which takes about 40 seconds to complete, during these 40 seconds, all commands are blocked and are executed only after this function returns (and dont work because interaction expired)

new_results = await kurokami.main({"i": item_name, "p": 1, "o": new_filename, "t": False, "s": False, "c": last_file_path})
#
class Query():
    def __init__(self, name, cid, delay: float):
        self.name = name
        self.channel = cid
        self.delay = delay

    @tasks.loop(seconds=120) # BUG: Should be self.delay
    async def cb(self):
        s = time.time()
        await self.query_cb()
        print(f"{self.name}, time taken: {time.time() - s}")

thread = Query(name=item, cid=cid, delay=delay)
thread.cb.start()
sturdy fractal
quick gust
#

tasks are async functions and don't block

hot sparrow
#

then i wonder why blocking is occuring

dense kindle
#

Hii I'm a beginner here

#
 embed=discord.Embed (title="Sample Embed", 
 discord.Embed.set_author(name=user.name)                   
 description="Hello world", color=0xFF5733)
 await interaction.response.send_message(embed=embed)```
#

can anyone tell me how to set the author name as the one who excuted the command

dense kindle
dense kindle
quick gust
hot sparrow
quick gust
hot sparrow
#
  embed=discord.Embed(title="Sample Embed",
  description="Hello world", 
  color=0xFF5733)
  embed.set_author(name=interaction.user.name)          
hot sparrow
quick gust
#

what library is that?

hot sparrow
#

set_author(name=interaction.user.name, icon_url=interaction.user.display_avatar)

dense kindle
quick gust
#

no I'm talking about the code sent by @hot sparrow

dense kindle
#

oh

hot sparrow
quick gust
#

if I'm not wrong, display_avatar was changed in dpy 2.0

hot sparrow
#

its a web scraper with selenium

quick gust
#

so you're not using dpy?

hot sparrow
#

let me check

quick gust
#

yes the discord api wrapper ure using

dense kindle
hot sparrow
dense kindle
hot sparrow
dense kindle
#

how to set the colour of the embed with a desired hex code?

#

other hex codes rather than discord's own available colours

quick gust
hot sparrow
#
color=0xFF5733

this can be changed to any 24 bit hex

dense kindle
#

okay thank you

dense kindle
#

is there anything wrong with this?

 embed=discord.Embed (title="Sample Embed", 
 embed.set_author(name=interaction.user.name, icon_url=interaction.user.display_avatar)                 
 description="Hello world", 
 color=0xFF5733)
 await interaction.response.send_message(embed=embed)```
naive briar
#

Why is there a embed.set_author in the embed constructor

proven timber
#

i have install ffmpeg and path it but i still get this err here:https://srcb.in/EsAAHMCH90

File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\player.py", line 183, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.?[0m

quick gust
naive briar
#

No

quick gust
#

async def embed

naive briar
#

Hmmmm

quick gust
#

I thought I was tweakin

young dagger
quick gust
radiant heath
#

yo anyone got any clue why i have to await my with opens lmao ?

@bot.command()
async def download(ctx, url):
    r = requests.get(url)
    filename = url.split("/")[-1]
    try:
        with open(filename, "wb") as f:
            f.write(r.content)
            pass
        await ctx.send(f"File '{filename}' downloaded successfully.")
    except FileNotFoundError:
        await ctx.send(f"File '{filename}' not found.")
    except Exception as e:
        await ctx.send(f"An error occurred while downloading '{filename}': {e}")
slate swan
#

i dont see you awaiting any with open

radiant heath
# slate swan i dont see you awaiting any `with open`

oop sorry completely forgot to send my error:

C:\Users\notsl\Desktop\rat\main.py:352: RuntimeWarning: coroutine 'Command.__call__' was never awaited
  with open(filename, "wb") as f:
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
#

so would awaiting it fix my issue ?

slate swan
#

most likely you have a command named open

radiant heath
#

oh fuck me

slate swan
#

which is overriding the open function

radiant heath
#

youre right

#

ive been confused for literally so long

#

tysm lmao i feel so stupid 🙏

slate swan
#

if you want to keep the name you can use name="open" inside decorator

#

and change the function name

thorn beacon
#

Where can I host a bot 24/7 for free? Like on which platform?

thorn beacon
#

The user runs a command called !host.

The bot then ask for information. How do you store the user input and use it in the code?

thorn beacon
#

E.g.

#

User does !host

#

Bot: Event Number:

#

User answers: 1222

#

Bot: Date

#

User answers: 20/03/2024

#

Smth like that.

slate swan
#

i would use a database

thorn beacon
#

In the end both posts in a channel:

Ladies and gentlemen,
User is hosting an event on date at time.

slate swan
#

oh like that?

thorn beacon
#

Yh

slate swan
#

ok one second

thorn beacon
#

The channel it posts is different to where the user uses command.

slate swan
#
import discord
from discord.ext import commands

bot = commands.Bot(command_prefix='>', intents=discord.Intents.all())

@bot.command()
async def host(ctx, eventnumber, date):
    eventchan = ctx.get_channel(1234567890) # your channel id
    await eventchan.send(f'Ladies and gentlemen,\n**{ctx.author.name}** is hosting and event on {date}')
#

thats how i would do it

thorn beacon
#

Alright, next question.

slate swan
#

go on

thorn beacon
#

So here is a message the bot posts in a channel:

#

Ladies and Gentlemen,
React to which you can attend.

#

The bot should auto add reactions 1,2,3,4,5,6 etc

#

And then if a user reacts

#

It should add them to the sheet behind the number

#

So if I reacted to one

#

Ladies and Gentlemen,
React to which you can attend.

  1. @thorn beacon
#

That's how it should look like

#

Same for unreacting.

slate swan
#

that would have to be used as a @bot.event

thorn beacon
#

A user first does !schedule command

slate swan
#

i havent coded a discord bot in a while so i would have no idea how to any of that unless i went and looked at an old bot

thorn beacon
#

Then it posts the sheet

#

And then they react to it

thorn beacon
#

Not many are experienced in this.

slate swan
thorn beacon
#

So my options for help are limited.

slate swan
#

it would be a hot second though

thorn beacon
#

Alr

slate swan
#

this is actually kinda complicated, when do you need this bot by?

thorn beacon
#

I have a bot, just this functionality is needed and the command.

#

Probs by like 5 days time or so.

slate swan
#

by when?

#

ok can i get back to you in two days or so? im kinda busy tomorrow, so it will either be tonight or then

thorn beacon
#

Alr nw.

#

Ty!

slate swan
#

ok accept my friend request and can you invite me to a server with the bot?

thorn beacon
#

Sure.

slate swan
#

thanks!

ionic garden
#

is it gine to still be using @commands.hybrid_command in 2024?

golden portal
#

yes?

marsh temple
#

I maked my discord bot and it's not replying in server. I made 2 commands and 1 trigger, trigger is working but commands not and trigger was working on dm only

#

Give me solution plz

naive briar
#

Uhhh

#

That's confusing

#

Did you enable the message_content intent?

slate swan
#

!msg 1145245248247836713 hi it isnt working

#

can anyone help?

#
async def msg(ctx, user_id: int, *, message: str):
    print("Command triggered.")
    print("User ID:", user_id)
    print("Message:", message)
    try:
        user = await bot.fetch_user(user_id)
        print("User:", user)
        if user:
            embed = discord.Embed(title="New Message", description=message, color=0xffcc00)
            embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
            await user.send(embed=embed)
            await ctx.send(f"📬 Message sent to **{user.display_name}** successfully!")
        else:
            await ctx.send("❌ User not found!")
    except discord.Forbidden:
        await ctx.send("❌ Unable to send message to the user!")```
naive briar
slate swan
naive briar
#

Do you have an error handler or logging setup?

naive briar
#

I can't fix anything if I don't know what even is the problem

viscid hornet
#

reactions are outdated af anyway

naive briar
#

Bold claim

viscid hornet
viscid hornet
#

why would you want like 5 reaction checks when you can just have a view with 5 buttons and add some logic so people can't pick the same spot

viscid hornet
naive briar
#

You can add reactions and process them dynamically

#

Not just hard code them. But yeah, buttons are probably the easier way anyway

thorn beacon
viscid hornet
# thorn beacon How would that work to my need?
#

the gist is you have a view and then add things to that view called items

#

i say items because you can have a range of things, like select menus, buttons and more

#

check out the links and lmk if you need extra help

slate swan
#

How to fix it?

viscid hornet
#

im so good

naive briar
unkempt canyonBOT
#
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.

naive briar
#

(in the code also :P)

slate swan
#

damn ty

vapid parcel
slate swan
#

4fun

sturdy fractal
dense swallow
#

how many rules can a discord bot add for automod for a server?

cyan eagle
#

How to read embeds ?

#

!embeds

#

!embed

dense swallow
#

!d discord.Message.embeds

unkempt canyonBOT
cyan eagle
#
    # Check embeds for the star symbol
    for embed in message.embeds:
        if '★' in embed.description or '★' in embed.title:
            await message.channel.send('yooo!')
        for field in embed.fields:
            if '★' in field.name or '★' in field.value:
                await message.channel.send('yooo!')

    await bot.process_commands(message)

cyan eagle
dense swallow
#

any errors?
if so send that first

cyan eagle
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='', intents=intents)

@bot.event
async def on_ready():
    print('Logged in as {0.user}'.format(bot))

@bot.event
async def on_message(message):
    if '★' in message.content:
        await message.channel.send('yooo!')

    for embed in message.embeds:
        if '★' in embed.title or '★' in embed.description:
            await message.channel.send('yooo!')
        for field in embed.fields:
            if '★' in field.name or '★' in field.value:
                await message.channel.send('yooo!')

    await bot.process_commands(message)

bot.run('your_token_here')
#

why bot not responding to embed text

quick gust
#

can u show what the embed looks like?

cyan eagle
#

and in description sending ★

dense swallow
cyan eagle
dense swallow
#

u put an empty string there

cyan eagle
dense swallow
#

ik, but have u tested it by using a prefixed cmd?

cyan eagle
#

yes bot is responding to normal message

#

like if i send ★its reapond yoo!

dense swallow
#

did u try removing that last line? bot.process_commands()?

cyan eagle
#

yep it was there before

#

not there*

#

you check if it works for you?

dense swallow
#

hm, add if message.embeds: then indent the for loop and other things, thats better practice

#

also does the bot have neccessary perms in that channel ?

cyan eagle
#

it is responding to normal text tho

#
import discord
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='', intents=intents)

@bot.event
async def on_ready():
    print('Logged in as {0.user}'.format(bot))

@bot.event
async def on_message(message):
    if '★' in message.content:
        await message.channel.send('yooo!')

    if message.embeds:
        for embed in message.embeds:
            if '★' in embed.title or '★' in embed.description:
                await message.channel.send('yooo!')
            for field in embed.fields:
                if '★' in field.name or '★' in field.value:
                    await message.channel.send('yooo!')

    await bot.process_commands(message)

bot.run('your_token_here')
cyan eagle
dense swallow
#

can u send ss of how the embed looks

dense swallow
#

the star is in the title or the field?

cyan eagle
#

title

dense swallow
#

are u sure its not set_author?

cyan eagle
#

wait 1 sec let me check

dense swallow
#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
cyan eagle
#

There i put 1 in footer and dec

#

but not responding

#

its responding to normal text tho

dense swallow
#

the code looks fine

#

try printing things in between to check

#

like this ```py
if message.embeds:
print("Embeds found")

cyan eagle
# dense swallow like this ```py if message.embeds: print("Embeds found") ```

2024-03-27 15:35:29 INFO     discord.client logging in using static token
2024-03-27 15:35:31 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 790b1b74a2d28cebd65e4b333a492522).
Logged in as Lucario.#4360
Received message: 
Received message: ★
Star symbol found in message content
Received message: yooo!
2024-03-27 15:36:34 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "★" is not found```
dense swallow
cyan eagle
#

Yes sir

#

it reads that embed is here but it cant read what's inside it

dense swallow
cyan eagle
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='', intents=intents)

@bot.event
async def on_ready():
    print('Logged in as {0.user}'.format(bot))

@bot.event
async def on_message(message):
    print('Received message:', message.content)
    if '★' in message.content:
        print('Star symbol found in message content')
        await message.channel.send('yooo!')

    if message.embeds:
        print('Embeds found in message')
        for embed in message.embeds:
            print('Checking embed:', embed.title)
            if '★' in embed.title or '★' in embed.description:
                print('Star symbol found in embed title or description')
                await message.channel.send('yooo!')
            for field in embed.fields:
                if '★' in field.name or '★' in field.value:
                    print('Star symbol found in embed field:', field.name)
                    await message.channel.send('yooo!')

    await bot.process_commands(message)

bot.run('your_token_here')
dense swallow
#

hm

#

try changing ur intente ```py
intents = discord.Intents.default()
intents.messages = True
bot = commands.Bot(command_prefix='', intents=intents)

cyan eagle
#

after login it has a message received as null look up

dense swallow
#

no

cyan eagle
#

Ok let me try

dense swallow
unkempt canyonBOT
#

class discord.Intents(value=0, **kwargs)```
Wraps up a Discord gateway intent flag.

Similar to [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions), the properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools.

To construct an object you can pass keyword arguments denoting the flags to enable or disable.

This is used to disable certain gateway features that are unnecessary to run your bot. To make use of this, it is passed to the `intents` keyword argument of [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

New in version 1.5.
cyan eagle
thorn beacon
#
@app_commands.describe(flight_number = "Enter number after AA.", departure = "Departure Airport.", date = "Enter Date.", time = "Enter Time.", aircraft = "Enter Aircraft.", arrival = "Enter Arrival.", gate = "Enter Gate.")

async def boards(interaction: discord.Interaction, flight_number: str, departure: str, date: str, time: str, aircraft: str, arrival: str, gate: str):```

Whats wrong here?
naive briar
#

Well, what's wrong with it?

thorn beacon
#

I cant see the slas cmd in discord.

#

It doesnt appear.

naive briar
#

Did you sync the tree?

thorn beacon
#

How?

#

How do you sync or what do you mean?

thorn beacon
#
@commands.is_owner()
async def sync(ctx: commands.Context) -> None:
    """Sync commands"""
    synced = await ctx.bot.tree.sync()
    await ctx.send(f"Synced {len(synced)} commands globally")
    
@bot.tree.command(name="boards", description="The bot to manage flight schedules.")
@app_commands.describe(flight_number = "Enter number after AA.", departure = "Departure Airport.", date = "Enter Date.", time = "Enter Time.", aircraft = "Enter Aircraft.", arrival = "Enter Arrival.", gate = "Enter Gate.")```


Like this? @naive briar
naive briar
#

Sure

thorn beacon
#

Doesnt work

#

@naive briar ^

naive briar
thorn beacon
#

The /boards

thorn beacon
shrewd apex
#

if so u might wanna close and restart discord if it still doesn't show up

thorn beacon
#

My goal is to open a channel when a user does /boards and then post the buttons there

#

So I did.

async def dep(interaction:discord.Interaction)
guild = interaction.guild
channel = guild.create_channel etc.

How do I send messages in this new channel via bots?

fiery girder
#

how can i make a discord bot use my live audio and stream it

leaden olive
#

why isnt it editing the embed?

ionic garden
#

the real question here is why you're editing the embed

velvet sierra
#

someone know how to update this list of commands?
i've tried await client.tree.sync() but it did not changed anything

slate swan
#

You could try refreshing/restarting your discord client

#

(The app, not bot)

shrewd apex
#

^^

thorn beacon
#

channel = await guild.create_text_channel(f"{interaction.user.name}-flight", category = category, overwrites = overwrites)

Why does an error pop up?

naive briar
# thorn beacon

The target variable is None. And None has no attribute named id 🫠

unkempt canyonBOT
#

discord/guild.py lines 1238 to 1243

for target, perm in overwrites.items():
    if not isinstance(perm, PermissionOverwrite):
        raise TypeError(f'Expected PermissionOverwrite received {perm.__class__.__name__}')

    allow, deny = perm.pair()
    payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}```
slate swan
#

looks like your overwrites contains None value

naive briar
#

Ah

velvet sierra
slate swan
#

turning discord off and then turning it on again

velvet sierra
#

ooooh got it

velvet sierra
#

guys, i'm kinda old, why people are using interaction: discord.Interaction with await interaction.response.send_message()
instead await ctx.send?

hushed galleon
vestal acorn
#

interactions allow you (with other things) to answer commands with ephemeral messages (blue and only visible by you)

hushed galleon
#

their similarities/differences are a result of dpy getting forked at around the time where 2.0 alpha only had interactions for message components (buttons and selects) before it was temporarily discontinued

sharp dome
#

hello

#

I need help with python

#

I can make an OOP system using different file to create a discord bot?

balmy bison
#

@hushed galleon

sharp dome
vestal acorn
#

no, but you can group commands in cogs

#

if you want, you can create a cog for every command but that's really useless

sharp dome
#

like i have balance, balance has many commands, like addbalance, removebalance, balance ect...

vestal acorn
#
import discord
from discord.ext import commands

class Ticket(commands.Cog):
  def __init__(self, client):
    self.client = client

  @app_commands.command(name = "open")
  async def open_ticket_command(self, interaction):
    await interaction.guild.create_text_channel(name = f"ticket-{interaction.user.name}")
    await interaction.response.send_message("ticket created", ephemeral = True)

async def setup(client):
  await client.add_cog(Ticket(client))```
#

short example

balmy bison
#

@sharp dome

sharp dome
#

this is like only for understanding it

vestal acorn
#

yup

#

and you load it in your main file

sharp dome
#

alr

sharp dome
vestal acorn
#

yeah

sharp dome
vestal acorn
#

👍

thorn beacon
#

Whats wrong in following code:

                                ,"2️⃣":{"role_id":1200803662268743770, "limit":1}
                                ,"3️⃣":{"role_id":1200803740660277318, "limit":1}
                                ,"4️⃣":{"role_id":1200803835359264788, "limit":1}
                                ,"5️⃣":{"role_id":1200804092394622976, "limit":4}
                                ,"6️⃣":{"role_id":1200804194748223521, "limit":1}
                                ,"7️⃣":{"role_id":1200804273982820423, "limit":2}}
                reaction_counts = {emoji:0 for emoji in emojis_roles.keys}
                for emoji in emojis_roles.keys():
                    await reaction.add_reaction(emoji)
                
                @bot.event
                async def on_reaction_add(reaction, user):
                    emoji = reaction.emoji
                    if emoji in emojis_roles:
                        role_id = emojis_roles["role_id"]
                        role = discord.utils.get(user.guild.roles, id=role_id)
                        if role:
                            if role not in user.roles:
                                limit = emojis_roles[emoji]["limit"]
                                if reaction_counts[emoji] >= limit:
                                    await reaction.remove(user)
                                else:
                                    reaction_counts[emoji] += 1
                
                @bot.event
                async def on_reaction_remove(reaction, user):
                    emoji = reaction.emoji
                    if emoji in emojis_roles:
                        reaction_counts -= 1```
#

My goal is for the bot to add reaction to a message in the channel.

#

Only users with the role for each emoji, can react. The limit is also set. But the error shows up. Let me capture it rq.

sharp dome
#

Added None cog,

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")
    try:
        cog = await bot.add_cog(AddBalance(bot, user_data_manager))
        print(f"Added {cog} cog")
    except Exception as e:
        print(f"Failed to add AddBalance cog: {e}")
    try:
        synced = await bot.tree.sync()
        print(f"Synced {synced} commands")
    except Exception as e:
        print(f"Failed to sync commands: {e}")
#
class Balance(commands.Cog):
    def __init__(self, bot, user_data_manager: user_data.UserDataManager):
        self.bot = bot
        self.user_data_manager = user_data_manager
#
@commands.command(
        name="add_balance",
        description="Add balance to a user",
    )
    async def add_balance(self):
#

what did i do wrong?

import discord
from discord.ext import commands
thorn beacon
#

Can someone help me? I want to set a limit of users as well as a role restriction per emoji. Of one of those requirements fail, it removed the users reaction from the message.

#
                                ,"2️⃣":{"role_id":1200803662268743770, "limit":1}
                                ,"3️⃣":{"role_id":1200803740660277318, "limit":1}
                                ,"4️⃣":{"role_id":1200803835359264788, "limit":1}
                                ,"5️⃣":{"role_id":1200804092394622976, "limit":4}
                                ,"6️⃣":{"role_id":1200804194748223521, "limit":1}
                                ,"7️⃣":{"role_id":1200804273982820423, "limit":2}}
                reaction_counts = {emoji:0 for emoji in emojis_roles.keys()}```
#

What I have so far.

#

This adds the reaction to the message.

sharp dome
#

there is no commands

#

and the cog dones't get added help!!!

thorn beacon
#

This is just an extract.

balmy bison
thorn beacon
#

The cmds don't bother me rn.

sharp dome
thorn beacon
#

Oh

snow knot
#

hey

#

since when we can do discord bot with python ?

quick gust
#

a long long time...

quick gust
#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message_edit), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Reaction.message).

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions) to be enabled.

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add) if you need this and do not otherwise want to enable the members intent.
next zinc
#

Hello everyone, I have a problem with the Python ticket bot and I would like to add it to VPS Ubuntu so that it works in the background. Can anyone help me?

slate swan
zenith yarrow
#
  @app_commands.command()
  async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
    
    c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
    conn.commit()
    await interaction.response.send_message("done",ephemeral=True)``` 
I want the bot to react with the emoji to the message whose id is taken
golden portal
# next zinc Hello everyone, I have a problem with the Python ticket bot and I would like to ...

you can just use a process manager like systemd, create a service, enable it, then start it, could do something like ```ini
[Unit]
Description=Your Bot Name
After=network-online.target

[Service]
Type=simple
WorkingDirectory=/dir/to/your/bot/path
ExecStartPre=source /dir/to/your/bot/path/.venv/bin/activate # assuming you use venv
ExecStart=python /dir/to/your/bot/path/main.py
User=your-user
Restart=always

[Install]
WantedBy=multi-user.target

vapid parcel
#

anyone have a working twitch bot? That does notifications for when someone goes live?

#

The twitch api is so confusing and if anyone has a working one then that would be great.

viscid hornet
viscid hornet
viscid hornet
sharp dome
sharp dome
#

I might make stupid mistakes

viscid hornet
viscid hornet
balmy bison
balmy bison
#

How it looks like:

#

How we want it to look like:

slate swan
#

Afaik no

balmy bison
slate swan
#

As far as I know you can't

balmy bison
#

oh alr, thanks

slate swan
#

It would only resize itself depending on the amount
of content in the embed

viscid hornet
balmy bison
viscid hornet
#

so:
embed = discord.Embed(
description = “hi”
)
embed.set_author(name = “hello”)

#

(no formatting bc im on my iphone)

sharp dome
#

yea I thought about it, but he changed the idea lol

zenith yarrow
snow coral
#

what would i use to get all the members who reacted to a message

autumn pewter
#
import discord
from discord.ext import commands
import datetime

welcome_channel = 1221421626202001470

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

client = commands.Bot("~", intents=intents)

@client.event
async def on_connect():
    print("connected")

@client.event
async def on_member_join(member):
    channel = client.get_channel(welcome_channel)
    embed = discord.Embed(
        description=f'Welcome to the official GAM3 discord server **{member.mention}**!',
        color=0x000000,
        timestamp=datetime.datetime.now(),
    )
    channel.send(embed=embed)

why is this not posting?

golden portal
unkempt canyonBOT
#

async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) representing the users that have reacted to the message.

The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake) abc.

Changed in version 2.0: `limit` and `after` parameters are now keyword-only.

Examples

Usage...
golden portal
golden portal
#

add what

autumn pewter
#

the await and other thing

#

in the code

golden portal
#

you can enable members intents by just doing intents.members = True and enabling them in the discord developer portal

#

for awaiting, you just await them for channel.send

balmy bison
#

@sharp dome ask abt timed reactions

sharp dome
#

I'm making a discord embed which need to edit it self after some time

#

but in python the timer task like java doesn't exists, and the way i do it's pretty wrong

#
 async def run(self, interaction):
        if self.seconds > 0:
                await interaction.response.send_message(embed=self.create_embed())
            self.seconds -= 1
        else:
            await interaction.edit_original_response(embed=self.create_embed())
#
 async def schedule_task(self, interaction):
        start_time = time.time()
        seconds = self.seconds
        while time.time() - start_time < seconds:
            await self.run(interaction)
            time.sleep(1)
balmy bison
unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

pale zenith
#

also for what it's worth, you shouldn't use time.sleep, it is blocking

balmy bison
#

@sharp dome

inner barn
#

I Made a Discord Bot, It Sends Messages with the Button, I Close and Open the Bot, Button Doesn't Work

sharp dome
#

it's doesn't created a loop

pale zenith
#

what?

sharp dome
#

I need a lop

#

it's just print 1 time, and then it stops

#

like uh?

pale zenith
#

well, you can't respond to an interaction more than once

sharp dome
#

no

#

4

all of what the loop printe

pale zenith
#

what? show your current code please

sharp dome
#

it should go from 5 to 0, it just printed 4

balmy bison
sharp dome
#

@tasks.loop(seconds=5)
async def run(self, interaction):
if self.seconds > 0:
if not self.has_message_sent:
self.seconds_left = f"<t:{int(time.time() + self.seconds)}:R>"
self.message = await interaction.response.send_message(embed=self.create_embed())
self.has_message_sent = True
self.seconds -= 1
print(self.seconds)
else:
self.upgrade()
await self.message.edit(embed=self.create_embed())
self.ended = True

pale zenith
#

I suppose a tasks loop isn't what you want in this case then, disregard.

sharp dome
#

what do I need

balmy bison
sharp dome
#

ong python sucks, it doesn't have basic timer task 😭

balmy bison
sharp dome
#

no

balmy bison
#

@pale zenith ?

sharp dome
#

a timer task is, when the tasks run for a certain time, and it's what I need.

#

but python doesn't have it, it has a timer task that delays the task

pale zenith
#

like "do this 10 times every 10 seconds"?

sharp dome
pale zenith
#

for 5 seconds?

#

like do this code until a certain timeout is exhausted then stop

sharp dome
#

yes, If I understood

#

run a task for 5 seconds, with a delay of 1 second

pale zenith
#

so "do this 5 times every 1 second"

sharp dome
#

every 1 second it does something for 5 seconds of it life

sharp dome
pale zenith
#

I mean a for loop works

#
for i in range(5):
    await asyncio.sleep(1)
    # stuff
sharp dome
#

ok lemme try

snow coral
naive briar
#

You don't, you get them from somewhere, like a message

sharp dome
pale zenith
sharp dome
#

async def task(self):
for i in range(5):
await asyncio.sleep(1)
print(i)

4

naive briar
#

Try setting the flush argument of print to True

sharp dome
#

why it's does it 1 time...

naive briar
#

Huh

#

!e

import asyncio

async def something():
    for i in range(5):
        await asyncio.sleep(0) # testing only
        print(i)

asyncio.run(something())
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
naive briar
naive briar
#

Don't waste time

sharp dome
#

mine crash

#
Traceback (most recent call last):
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes_commands.py", line 42, in upgrader
    asyncio.run(upgrade_game_mode.task(interaction))
  File "C:\Python312\Lib\asyncio\runners.py", line 190, in run
    raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'upgrader' raised an exception: RuntimeError: asyncio.run() cannot be called from a running event loop
C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\app_commands\tree.py:1252: RuntimeWarning: coroutine 'UpgradeGameMode.task' was never awaited
  await self.on_error(interaction, e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
naive briar
#

Don't do that, I'm just testing. Should've done it in #bot-commands

sharp dome
#

the message it can be sent by anybody

So it need to know which one to edit

golden portal
#

🤔 but you can only edit your own bot's message

#

what are you trying to do anyway

viscid hornet
sharp dome
#

fixed

#

not usefull for the type i'm doing

viscid hornet
#

for interactions, use .response.edit_message

sharp dome
#

I have done it works perctly!

viscid hornet
viscid hornet
sharp dome
#

like easy lol

viscid hornet
viscid hornet
zenith yarrow
#

Someone said i need channel id too

viscid hornet
viscid hornet
#

you can always do await message.channel.send(…) to keep things readable and small

zenith yarrow
swift siren
#

i think i’m slow but how to fetch a users global display name change , I assumed its with on user update but i’m getting frustrated

viscid hornet
viscid hornet
#

await message.add_reaction(…)

zenith yarrow
balmy bison
viscid hornet
viscid hornet
#

otherwise idk

#

most decent VPSs cost money

#

theres no good free ones and all the free ones have a drawback

zenith yarrow
#

OH

#

Like split the message link

viscid hornet
#

i showed you the url format

zenith yarrow
viscid hornet
#

idk how to do it in regex but you can do it in python by splitting at ‘/‘ and then taking the last object with index -1

viscid hornet
viscid hornet
zenith yarrow
viscid hornet
zenith yarrow
#

No if I don't have message link but I have message id

viscid hornet
#

it goes /guild_id/channel_id/message_id

zenith yarrow
#

Is there a way

viscid hornet
#

and then to get the ID of that channel, add a .id to the end

zenith yarrow
viscid hornet
#

i think its bot.fetch_message

zenith yarrow
#

So I can fetch a message by its id and store it in a variable

#

And it'll give me the channel id

#

Am i wrong

viscid hornet
viscid hornet
viscid hornet
zenith yarrow
sharp dome
#

question

viscid hornet
sharp dome
#

there is the fileds where the user can put their own choice, but i wan there will be 2 choice to put how to do it

viscid hornet
#

hmm okay…

sharp dome
viscid hornet
sharp dome
#

something like that you will see heads and tails on the menu when you the slash command

sharp dome
#

like this

viscid hornet
#

let me find the link one sec

zenith yarrow
#
@app_commands.command()
  async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
    
    message = bot.fetch_message(int(message_id))
    
    await message.add_reaction(emoji)
    c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
    conn.commit()
    await interaction.response.send_message("done",ephemeral=True)```
#

@viscid hornet

#

Do it have to be
message = await channel.fetch_message(...)

viscid hornet
#

i said that

golden portal
#

bot.fetch_message doesnt exist

#

also the error is at line 48

viscid hornet
#

get_message then

golden portal
#

that doesnt exist either

viscid hornet
#

wait wtf

golden portal
#

you need a channel to get the message obj

viscid hornet
#

:blobabouttocry:

viscid hornet
#

indexing through all the trillions of messages would be a pain ngl 😭

zenith yarrow
viscid hornet
#

if so, use self.bot instead

zenith yarrow
viscid hornet
#

assuming your cog looks like py class Cog(commands.Cog): def __init__(self, bot): self.bot = bot

zenith yarrow
#
class reactionrole(commands.Cog):

  def __init__(self, bot):
    self.bot = bot

  @app_commands.command()
  async def reactionroleadd(self,interaction: discord.Interaction, role: discord.Role, emoji: str , message_id: str):
    
    message = bot.fetch_message(int(message_id))
    
    await message.add_reaction(emoji)
    c.execute("INSERT INTO reactionaldb VALUES (?,?,?)",(message_id,str(role.id),emoji))
    conn.commit()
    await interaction.response.send_message("done",ephemeral=True)
    ```
#

I've already done that

zenith yarrow
viscid hornet
zenith yarrow
#

Get message?

viscid hornet
#

ok so you have the link

#

a message link like this py [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/)

zenith yarrow
viscid hornet
zenith yarrow
viscid hornet
#

you use the channel ID in self.bot.get_channel() and then you can message from there

zenith yarrow
#

I'll come after completing by dinner

viscid hornet
sharp dome
viscid hornet
#

i went on my laptop and my mind instantly went black

#

@sharp dome this was one of the examples for an autocomplete ```py
@app_commands.command(...)
async def foo(interaction: discord.Interaction, bar: str):
...

@foo.autocomplete('bar')
async def autocomplete_callback(interaction: discord.Interaction, current: str):
# Do stuff with the "current" parameter, e.g. querying it search results...

# Then return a list of app_commands.Choice
return [
    app_commands.Choice(name='Option 1', value='Option 1')
]```
sharp dome
#

how to add button to an embed?

viscid hornet
sharp dome
#

example?, the button has some code on it to be handled

viscid hornet
sharp dome
# viscid hornet wdym by an enum
  @app_commands.command(
        name="coinflip",
        description="Flip a coin",
    )
    async def coinflip(self, interaction, side: CoinSide, amount: str):
#
class CoinSide(Enum):
    Heads = "Heads"
    Tails = "Tails"
#

see, enum!

viscid hornet
#

what the fuck am i looking at

viscid hornet
# sharp dome example?, the button has some code on it to be handled
class ConfirmOrCancel(ui.View):
    def __init__(self):
        super().__init__(timeout = None)
        self.selected = False
    
    @ui.button(label = "Yes", style = BS.green)
    async def confirm(self, interaction: Interaction, button: discord.Button):
        self.selected = True

        for item in self.children:
            item.disabled = True

            if item.label == button.label:
                item.style = BS.green
            else:
                item.style = BS.grey

        await interaction.response.edit_message(
            view = self, embed = discord.Embed(
                title = "Confirming Decision...",
                description = "You have selected `Yes` so we will be updating your diary. Give us a moment.",
                color = discord.Color.green()
            )
        )

    @ui.button(label = "No", style = BS.red)
    async def cancel(self, interaction: Interaction, button: discord.Button):
        for item in self.children:
            item.disabled = True

            if item.label == button.label:
                item.style = BS.green
            else:
                item.style = BS.grey

        await interaction.response.edit_message(
            view = self, embed = discord.Embed(
                title = "Cancelling Decision...",
                description = "You have selected `No` so we will be aborting the process of updating your diary. Give us a moment.",
                color = discord.Color.red()
            )
        )```
sharp dome
#

ok

viscid hornet
sharp dome
viscid hornet
sharp dome
#
 if side not in [CoinSide.Heads, CoinSide.Tails]:
            await interaction.response.send_message("invalid side. Must be heads or tails", ephemeral=True)
            return
#
if side is CoinSide.Heads:
   # do something
viscid hornet
#

i meant show the autocomplete code

sharp dome
#

there is no

#

it all of that

#

it does autmaticcally added those on it

balmy bison
#

this is the interaction we need made

viscid hornet
sharp dome
#

what library I need to have?

#
[2024-03-29 18:04:20] [ERROR   ] discord.ui.view: Ignoring exception in view <Confirm timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Confirm' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\xntro\PycharmProjects\ps99casino\.venv\Lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\xntro\PycharmProjects\ps99casino\game_modes\game_modes_commands.py", line 106, in confirm
    await interaction.response.send_message(embed=create_embed_coinflip)
          ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'response'
#

like

viscid hornet
sharp dome
# viscid hornet show your code
class Confirm(discord.ui.View):
    def __init__(self, user_data: user_data_manager, amount_to_float: float):
        super().__init__(timeout=None)
        self.user_data = user_data
        self.amount_to_float = amount_to_float

    @discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
    async def confirm(self, button, interaction):
        user = self.user_data.get_user(interaction.user.id)
        create_embed_coinflip = discord.Embed(
            title=":white_check_mark: Coinflip Created",
            description=(
                ":gems: **Gems**: {}\n"
                ":gems: **New Balance**: {}\n"
                ":crown~1: **Channel**: <#{}>"
            ).format(
                number_converter.number_to_suffix(self.amount_to_float),
                number_converter.number_to_suffix(user.balance - self.amount_to_float),
                cfg.FLIP_COIN_CHANNEL_ID),
            color=discord.Color.purple())
        create_embed_coinflip.set_footer(text=f"{cfg.BOT_NAME} - Coinflip Created")
        self.user_data.remove_balance(interaction.user.id, self.amount_to_float)
        self.user_data.add_wagered(interaction.user.id, self.amount_to_float)
        await interaction.response.send_message(embed=create_embed_coinflip)
viscid hornet
#

its interaction then button