#discord-bots

1 messages · Page 374 of 1

fast osprey
#

Is this a webhook or a channel you're trying to send to, very different things

#

also you should not be using requests in an async application or you're going to freeze your whole bot

copper flume
#

How do increase limit of bot.cached_messages?

drifting arrow
#

how do I set the paramater annotation to be a discord user or member?

#

nvm. I was using the role class xD

#

it's discord.Member not discord.member :D

ashen ocean
#

What would you guys say
what the best free website that keeps your discord bot on 24/7?

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

blazing beacon
#

the first sentence o_ob

golden portal
copper flume
#

okay

copper flume
#

like using jishaku

golden portal
copper flume
#

okay

elfin marten
#

Hey folks

#

Are there any popular open source Discord bots that query and display information related to Steam game servers?

golden portal
#

not sure what specific games do you wanna lookup on

elfin marten
# golden portal not sure what specific games do you wanna lookup on

It's strange because I was googling for these type of projects the other day and I only found one. It's 5 years and very outdated probably doesn't even work. I would have expected these type of bots to be very popular but when I think about it I've never even saw one like that on a Discord server before.

I'm hosting a game server for a new game that was released on June 1st and it has very few admin features yet, no plugin support, and no player list for people to see who's online. Lot's of my players wanted to be able to see a player list so I wrote a Discord bot that uses Steams query protocol to fetch information like server status and player list, etc. I am just asking because I'm thinking about making a gitlab and uploading it but I just really think I'm missing something... There has to be other bots doing this? It just seems like it would be something common but maybe not

elfin marten
golden portal
#

you could just lookup an A2S protocol library in python if you wanna query in your discord bot to your steam game, it's what steam supports from what i understood

limber jolt
#

Yo Im new to VS code and I know you have to pip install discord and stuff but would I have to do that with like os and random

limber jolt
upbeat otter
limber jolt
#

Okay

upbeat otter
limber jolt
elfin marten
limber jolt
# upbeat otter yes

One more think why when I press run without de bugging It de bugs and i cant find ou how to select a de bugger

normal linden
#

i need some help with website scraping and decryption and encryption can someone help?

shy eagle
#

yo anything wrong with this channel = client.get_channel(1253763547612315739) embed = discord.Embed(title=f"Join Logs", color=discord.Color.blurple()) embed.add_field(name="Register", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline=True) embed.add_field(name="Mention", value=member.mention, inline=True) embed.add_field(name="Member ID", value=member.id, inline=True) embed.add_field(name=f"Presence", value=member.status, inline=True) embed.set_thumbnail(url=guild.icon_url) embed.set_footer(text=f"Members Now ‣ {member.guild.member_count}") embed.set_author(name=f"{member.name}", icon_url=member.avatar) await ctx.send(embed=embed)

finite cave
#

why cant i use my command

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
intents.members = True
intents.presences = True

TOKEN = 'aint tellin you my token wtf'

bot = commands.Bot(command_prefix='/', intents=intents)


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


@bot.command(name='agree', help='Sends "I AGREE" as a message')
async def agree(ctx):
    await ctx.send('I AGREE')

bot.run(TOKEN)
slate swan
fast osprey
#

You almost certainly don't need all intents

hybrid light
#

Hello, how should I correctly check the inverter of member who joins

wanton current
#

You would have to store invites and who created them when they are created, and then when someone joins, check all the invites in the server and compare them to your stored invites to see which one increased.

vapid parcel
#

Not hating but uh, doesn't this just improve raid bots and nuking bots or whatever?

#

There was no reason for dpy adding this...

slate swan
vapid parcel
#

dpy could have not added it tho.

#

Thats just my opinion ig

slate swan
#

They're merely implementing what Discord allows to cover the entire API - just like other libraries

vapid parcel
#

Idk i just see a mad risk in that.

#

Nuke bots, everything

#

Really fucking stupid. Good shit discord.

#

Dpy could take it out and provide less support on that nuke bots stuff. But thats nothing they can control ig.

wanton current
#

lol, people can literally just send a manual api request using discord.py's internals even if it wasn't added as an official method

radiant pike
wanton current
#

you'll get rate limited if you ban 200 peope in a for loop really quickly

vapid parcel
vapid parcel
#

this eliminates that lmao. Not everyone can get proxies cuz some are stupid. So now they can just do bulk ban without worrying rate limits, and proxies.

#

See the issue now?

wanton current
#

also, raids aren't a problem if you manage your server correctly lmao

vapid parcel
#

So even if you manage your server properly. Doesn't mean the people who you have in your server that have admin or something are managed properly.

#

Yes you can make no one have admin

wanton current
#

How do you even manage to download a token logger in the first place

vapid parcel
#

Well actually here ill give an example that just happened the other day xD

restive flint
#

guys I want to learn

vapid parcel
#

So this random sent a link, saying test my game blah blah blah, you click the link, go to the website, and you are on the website. When you download it and you think its a fucking game you get token logged.

restive flint
#

how to make a discord bot what do I do?

#

where do I start

slate swan
#

If one library doesn't do it, the developers will use a different one which has it. Let discord.py cover the entire API lmao

vapid parcel
#

But if you actually see where the url takes you, its a discord url, so its kinda obvi its a token logger

wanton current
vapid parcel
vapid parcel
finite salmon
wanton current
vapid parcel
#

and you can get token logged on many things tbh. You can just get token logged on basic exes tbh. So mainly just download trusted sources atp

#

also if you download shit on github, read the source if its related to discord or sum.

#

Unless you know its trusted

finite salmon
vapid parcel
#

Most people get token logged cuz they think "oh its open source I can't get token logged right?"

finite salmon
#

good morning

vapid parcel
#

How you been? Haven't seen you in like 5 minutes.

finite salmon
#

I have been

vapid parcel
#

yo thats wild

finite salmon
#

fr

vapid parcel
#

thats crazy bro

finite salmon
#

how have you been

vapid parcel
#

just do

finite salmon
#

yo thats wild

vapid parcel
#

yeah ik

finite salmon
#

crazy shit

vapid parcel
#

ikr bro

finite salmon
#

farewell

radiant pike
restive flint
#

whats the difference between async def and normal def

radiant pike
restive flint
#

like a thread?

#

like you can multitask?

radiant pike
restive flint
#

uhm what about ctx?

#

like why do we need to call it ctx?

radiant pike
#

async doesn't run on multiple threads

radiant pike
restive flint
#

like can't I call it something else?

radiant pike
#

but thats the convention

restive flint
#

oh okay

radiant pike
#

but its weird to name the context param "dasoikjdoiasjdoi"

#

and makes harder development

restive flint
#

yeah

#

but like discord api is weird

#

it takes the function name as the command itself

radiant pike
restive flint
#

but like how do I make it understand when its lowercase too?

vapid parcel
restive flint
#

I don't get it?

vapid parcel
#

idk its just bad things

restive flint
#

like for example if I make a function called hello would it understand even if it was !HELLO

scarlet tiger
radiant pike
restive flint
#

what the hell is a decorator

radiant pike
scarlet tiger
restive flint
#
@bot.command(name="hi", commands=blabla) # <-- this
async def this_isnt_the_name(ctx):
  ...```
radiant pike
#

you just invented a parameter named commands lol

restive flint
#

no

radiant pike
#

yes

restive flint
wanton current
#

commands is the module you imported via from discord.ext import commands

radiant pike
restive flint
#

ohh

#

but how do I attach the command to the right function then?

wanton current
#

but without commands

restive flint
#

HUH

#

plus what the fuck does @bot do

scarlet tiger
restive flint
#

I am trying

#

this is it right?

scarlet tiger
#

or you can see examples in the discord.py repository

wanton current
restive flint
#

isn't the bot already the same

wanton current
#

well, bot.command is a method on your bot that basically adds the decorated function as a command, it's the same as doing:

async def my_command(ctx): ...

bot.add_command(my_command)
restive flint
#

because the documentation gave limited information

wanton current
#

what would it be otherwise

restive flint
wanton current
#

does it say Callable

#

oh

#

yeah, it should work wit a function

restive flint
#

It says usually

#

wtf does usually mean bro its a fucking code

#

does it decide on its own wtf

radiant pike
#

you rn:

restive flint
#

ty but my brain is fucked psl

scarlet tiger
# restive flint

If you want to add commands manually (not recommended), you can do it that way. Remember that the @bot.command(...) decorator does the work for you

wanton current
#

Basically everyone uses the decorator since it's easier and cleaner

wanton current
#

bot.add_command

restive flint
#

no like I understand that but is there another way or sum?

wanton current
#

you either do:

@bot.command()
async def abc(ctx):
    pass

or you do

async def abc(ctx):
    pass

bot.add_command(abc)
#

the first way is the recommended way

restive flint
#

so it just adds every single function that is underneath the @bot.command()?

wanton current
#

no it adds the function below

restive flint
#

only below?

wanton current
#

@bot.command()
async def abc(ctx):
    pass

@bot.command()
async def xyz(ctx):
    pass
``` two different commands
restive flint
#

hmm

#

python is weird in multiple ways

radiant pike
#

python decorators

restive flint
#

nah I got what decorators are

#

functions that returns shit

#

like return bot.add_command()

radiant pike
#

nop 😭

scarlet tiger
#

remember that a decorator takes the function and adds additional functions to it, but does not modify it directly.

restive flint
#

WHAT

radiant pike
#

a decorator completly overrides a function

restive flint
radiant pike
#

and can do multiple things with that function it got, like in this case use it to register a command

restive flint
#

OH

#

so they are fuınctions taking in functions?

scarlet tiger
#

I recommend that you first learn Python concepts before developing a discord bot.

void needle
#

Hey, any idea why this isn't working?

restive flint
#

so like instead of doing egfunction(anotherfunction())

dense falcon
#

Is there a way I can have an Optional Keyword argument? I have a command that looks a little like this, and while it works if I don't add anything after updateprofile, the bot halts saying that desc is a required argument. Can I prevent this?

radiant pike
scarlet tiger
radiant pike
#

liittle_giggle just practice until your fingers hurt

#

and search on google

void needle
#

and if not it will not respond ofc

wanton current
#

this is what the @bot.command decorator does internally:

#

self.add_command is the same as bot.add_command

restive flint
#

okay I got it

#

this time

radiant pike
#

if isinstance(chanel.type, discord.TextChannel):
...

void needle
#

You mean isinstance

#

yeah let me check

wanton current
#

isinstance(channel, discord.TextChannel)

radiant pike
#

yep

void needle
#

Still isn't working

wanton current
#

or you need to do isinstance(channel.type, discord.ChannelType.TextChannel

void needle
#

OHHHHH

#

Yeah that's what I was missing

wanton current
#

the former is just easier though

void needle
#

I was using discord.TextChannel instead of discord.ChannelType.TextChannel

#

Thank you

radiant pike
#

lol

restive flint
#

I didn't understand shit in the documentation about @event tho

wanton current
restive flint
wanton current
#

@fast osprey stop lurking

restive flint
#

(I just learned about self yesterday)

fast osprey
#

What's the actual question?

wanton current
#

thank you

restive flint
#

@event

fast osprey
#

it registers a callback for when that event happens

amber flare
#

Hey, not bot but discord webhook releated

am unsure on how to send photo in the webhook
i dont have a link, but a file saved on my pc

restive flint
wanton current
#

basically it makes it so when you run !command it runs that function

amber flare
radiant pike
restive flint
amber flare
#

id need an actual answer

wanton current
restive flint
radiant pike
#

thats abstraction

wanton current
#

Well, it does nothing by default, literally

async def on_ready(self):
    pass
restive flint
radiant pike
#

yep

restive flint
#

like add commands?

radiant pike
wanton current
#

🤨

radiant pike
restive flint
#

like what is the difference between

fast osprey
#

bot.listen registers a callback to run in addition to the default implementation

#

they effectively "stack"

restive flint
#
@bot.event()
async def on_ready():
    print("Bot Is Ready.")
    print("-------------")
@bot.listen()
async def on_ready():
    print("Bot Is Ready.")
    print("-------------")
restive flint
fast osprey
#

not really?

restive flint
#

but then what?

#

oh wait

#

so It runs both of them at once?

#

like it runs both functions at once but they are not related?

fast osprey
#

Not "at once" with how asyncio works

restive flint
#

but thats the main point right?

#

like it runs both of them

sick birch
#

yeah but not at the exact same time

radiant pike
restive flint
#

yeah I got it

wanton current
restive flint
#

wtf does this do *

wanton current
restive flint
#

python

wanton current
#

depends if it's *args or *, args

restive flint
#

like it just seperates arguements?

#

*args

scarlet tiger
wanton current
restive flint
#

ok figured that out

#

how do I know which channel a person sends message to?

wanton current
#

message.channel

restive flint
#

thanks

#

is message a string or no?

#

like how do I get the message in the message

restive flint
wanton current
#

message.content is a string

#

could really figure this out yourself yk

#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
restive flint
#

discord.Message?

#

no like for example

#

I am trying to make a responder here

#

like when someone says hello, I want the bot to say greetings

#

do I need to import intents to do that

#

its weird someone help

wanton current
#

You need message content intents to see message content, yes

void needle
#
for category in fromGuild.categories:
        newCategory = await toGuild.create_category(category.name, overwrites=category.overwrites)

        for channel in category.channels:
            if channel.type == discord.ChannelType.text:
                newCh1 = await newCategory.create_text_channel(name=channel.name)
                newCh1.overwrites = channel.overwrites

Error:
AttributeError: property 'overwrites' of 'TextChannel' object has no setter

#

Any idea why?

#

I'm trying to copy the overwrites from a channel to another

wanton current
#

you do channel.edit

spice warren
#

You can also pass overwrites on creation

restive flint
#

what are intents

wanton current
#

oh didnt see they created a channel

restive flint
#

wtf help me

void needle
wanton current
restive flint
#

okay ty

wanton current
#

eg. if you want content, enable Intents.message_content

spice warren
#

You were answered

spice warren
restive flint
#
intents: Intents = Intents.default
#

is this the only way?

spice warren
#

You can also pass overwrites into create_text_channel

wanton current
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.

void needle
#

And it shouldn't matter if I use channel.edit or use the channel as a variable to edit it

wanton current
#

updating an attribute in your python program won't automatically send an api request to Discord to edit it

spice warren
#

"didn't work" is not very helpful in resolving your issue
It does matter, since you'd be editing an object in memory whereas calling Channel.edit would perform the necessary api operation

#

Creating and then editing is a waste of ratelimits when create_text_channel supports an overwrites= argument

#

!d g discord.Guild.create_text_channel

unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel) for the guild.

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict) of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member) or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role)) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite) as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit) will be required to update the position of the channel in the channel list...
void needle
#

I know that it usually does, but it doesn't show up

restive flint
#

WHAT THE HELL IS CLIENT

void needle
#

Maybe it is because I'm using 1.7.0 version?

spice warren
#

A very unsupported version

void needle
#

Yeah I know, but is this the issue?

spice warren
#

No

#

It has always supported passing overwrites, as can be seen in the documentation, you're likely relying on bad intellisense

void needle
#

This worked, but didn't actually pass the overwrites

spice warren
#

await

void needle
#

oh s

restive flint
#

how do I make the bot send a message in a specific channel?

spice warren
#

The documentation will tell you it's a coroutine, but again, a waste of ratelimits since creation supports them

restive flint
#

I could make this only

wanton current
#

it's an attribute, not a method

restive flint
#

thanks

#

now how do I make the bot send a message to that channel

wanton current
#

await channel.send()

restive flint
#

wait is the message = str(message)

#

I think you can call message()

scarlet tiger
restive flint
#

why??

#

I don't understand shitttt

amber flare
#

PLEASE i am dying

how the fuck do i send image (not file) thro webhook with py

wanton current
#

an image is just a file

amber flare
#

i want it to not be download

#

but for it to show the image

restive flint
#

WHAT IS THE MESSAGE

#
@bot.event
async def on_message(message):
    channel = message.channel
    text = message()```
#

IS TEXT THE MESSAGE?

wanton current
restive flint
#

I AM TRYING TO DETECT WHAT A PERSON HAS SENT

wanton current
# amber flare

how are you sending it because an image isn't 10 bytes

restive flint
amber flare
wanton current
restive flint
amber flare
#

and idk

wanton current
amber flare
#

it opens fine lol

amber flare
wanton current
restive flint
#

got it

#

am I doing this right?

amber flare
#

when i click on it, it opens the image

restive flint
amber flare
#

am asking about my own issue.

restive flint
#

bro just a line of code where I get the bot

#

couldn't bother you at all

restive flint
amber flare
#

i dont even do discord bots bro

restive flint
#

oh wait I remember now

trim tulip
#

Is there a setting that will prevent this from appearing when a new person joins a server?

restive flint
trim tulip
#

that is hella stupid

wanton current
restive flint
#

yes

scarlet tiger
restive flint
#

RuntimeError: Event loop is closed

restive flint
wanton current
restive flint
#

RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x0000025866839670>
Traceback (most recent call last):

scarlet tiger
wanton current
#

that's not the entire thing

#

have you tried reading what it says

restive flint
#

oh wait

#

no I didn't see

#

but how do I enable it

wanton current
#

you go into the link and selec your bot and then go to the Bot tab and turn on the checkboxes for the intents that you're requesting in your code.

restive flint
#

ok got it

#

I managed to make it to work

#

first discord bot ever smh

#

the command isn't working

#

WHY

wanton current
#

how are you running it

restive flint
#

nebokayarıyon

#

I tried >explainUses too

restive flint
wanton current
#

you changed the name with name=

#

so you need to invoke it with that

restive flint
#

what?

#

I tried both

restive flint
#

is it beacause of the ı

wanton current
#

idk

restive flint
#

that wasnt the issue

#

then wtf is ?

wanton current
#

try to remove the name= and use it with >explainUses

restive flint
#

nop

#

it didn't work for some reason

restive flint
#
import discord
from discord.ext import commands
from discord import Intents

needs = Intents.default()
needs.message_content = True
needs.members = True

bot = commands.Bot(command_prefix=">", intents=needs)

@bot.event
async def on_ready():
    print("Bot Is Ready.")
    print("-------------")

@bot.command(name="nebokayarıyon")
async def explainUses(ctx):
    await ctx.send("Yazdığınız salakça şeyleri zorbalıyorum")

@bot.event
async def on_message(message):
    channel = message.channel
    text = message.content
    if text.lower() == "nabıyonuz la":
        await channel.send("sana ne yarram")```
#

heres everything

#

I deleted the run btw

wanton current
#

oh

#

change your @bot.event to @bot.listen

#

on the on_message

restive flint
#

why?

#

is it a method?

wanton current
#

because you're overriding the default functionality which is checking for commands, alternatively you can run bot.process.commands() in your on_message

restive flint
#

do I need to call it?

restive flint
#

yes we do call it

#

thank you I'll be taking my leave for today

#

I really appreciate the help

wanton current
#

no worries

amber flare
sturdy egret
#

Need some discord bot help, ping me if you can. I got some payment for you.

worthy saffron
sly hamlet
#
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.user' raised an error: TypeError: callback 'user.useable_only_users' must have more than 1 parameter(s)``` ```py
    @app_commands.command(name='ping',
                       description="Ping of the bot.")
    @app_commands.allowed_installs(guilds=False, users=True)
    @app_commands.allowed_contexts(guilds=True, dms=True, private_channels=True)
    async def useable_only_users(interaction: discord.Interaction):
        await interaction.response.send_message("I am only installed to users, but can be used anywhere.")```
#

Does anybody have any ideas on how to fix this? Slash commands with a new release last night and I cannot seem to figure this out even after reading documentation

hushed galleon
spice carbon
#

hey guys! i am having some issues with some emojis here. i have this json:

{
    "tier_1": {
        "name": "Tier 1",
        "price": 7.50,
        "emoji": "\\U0001f4e6"
    },

    "tier_2": {
        "name": "Tier 2",
        "price": 22.0,
        "emoji": "\\U0001f6e0"
    }
}

and i want to get this emoji and display it on a dropdown:

        for product_id, product in self._load_products().items():
            options.append(
                discord.SelectOption(
                    value=product_id,
                    label=product["name"],
                    emoji=discord.PartialEmoji(name=product["emoji"]),
                    description=f"\N{BANKNOTE WITH DOLLAR SIGN} ${product['price']} | R${usd_to_brl(product['price'])}",
                )
            )

however this code is giving me a invalid emoji exception over and over, and i am not sure why. when i print the emoji it is a escaped sequence tho, probably has something to do with it. but other than escaping it i am not sure wheter i can store emojis on json or not

restive flint
#

guys what are guilds?

pale zenith
merry cliff
#

fr why would they call it the same thing

upbeat otter
#

What does it do?

merry cliff
upbeat otter
#

aight thanks

merry cliff
#

np

upbeat otter
#

wtf are they doing this is so confusing

merry cliff
#

exactly lol

restive flint
#

can anyone with the knowledge of classes take a look?

slate swan
#

It's unrelated to discord bots, so nothing to do with this channel. Have patience

#

Especially for such basics, there are lots of people that can help if you wait

drifting arrow
#

Using a discord looping task, how would I grab a specific role (by id) and a specific user (by id)?

#

drawing a mental blank ;-;, i know there's a way

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
quasi bough
#

!d discord.Client.get_user

unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
quasi bough
#

avoid utils.get unless you don't have any other choice

copper flume
#

__init__.py

async def setup(bot):
    await bot.add_cog(Events2(bot))

    await bot.add_check(Events2(bot).ignore_check)```
`events2.py`
```py
async def ignore_check(self, ctx): ...

Is it a good practice?

restive flint
#

yesterday I added my bot to my testing server and now I can't add it to my own server its asking me for a redirect URL which I hadn't passed in YESTERDAY

#

why is it asking me for this now?

#

plus even after I add it

#

it says unvalid form body

merry cliff
merry cliff
copper flume
restive flint
#

I didn't do anything

merry cliff
#

anything OAuth2 related?

restive flint
#

no

merry cliff
restive flint
#

oh wait my bad

copper flume
#

okay.

restive flint
#

what do I do

merry cliff
#
if message.author.bot:
    return```
#

ignores all bot messages

restive flint
restive flint
#

cya

fast osprey
#

Depending on how many messages are in the channel this may take a very long time. What's the use case?

rugged shadow
#

you could just delete the channel and make a new one with the same metadata

fast osprey
#

Most of the time this comes from an ocd need to keep channels "clean" when it's also just incredibly easy to not read messages

#

Deleting channels causes a bunch of destructive side effects that don't make that worth it in most cases

haughty summit
#

Hello Everyone

#

I am facing some problems related with threads and concurrency on a discord bot implemented using discord module library in python. Fetching data is involved for each user request so my problem is not being able at this point to prevent users to throw several commands

#

I was thinking about mutexes but dont know if complicated it more than needed

#

I would highly appreciate getting some help as I am blocked at this point

rugged shadow
#

you don't want your bot to process multiple commands at once?

#

i think you want a queue or a ratelimiter

fast osprey
#

Which discord module? There are several libraries that implement it

#

Would also be helpful to know what data you're fetching, and what the problem is that is arising from doing so

haughty summit
haughty summit
haughty summit
#

My condition three is being implemented in the on_message function and launching a task for the command checker that ends calling the function for the specific command and fetch associated

slim bloom
#

what is best for my discord bot

async with aiohttp.ClientSession() as session:
    await session.post(url, headers=headers, json=json)

async with aiohttp.ClientSession() as session:
    async with session.post(url, headers=headers, json=json) as response:```
fast osprey
#

What are these "issues"? We can't really solve them in general terms

#

It's quite possible that some degree of caching is part of your answer here

haughty summit
#

I may not understand properly the execution model of on_message function but my issue is triggering several consecutive fetches from an user that sent 4 consecutive commands, just wanted to test this situation and protect the bot for that, implemented a cooldown period based on a timer that wouldnt let user tu run more than once

fast osprey
#

But what is the actual issue

#

is there an error? A behavior you don't want?

lucid ember
#

Any idea why entry.before only prints this text? <AuditLogDiff>

This is the code I'm using:

async for entry in guild.audit_logs(action=discord.AuditLogAction.member_move):
        if modRole in entry.user.roles:
            print(f"Moderator: {entry.user}\nUser: {entry.target}\nBefore: {entry.before}")```
fast osprey
#

Because that's what it is, an AuditLogDiff

#

the repl of an object isn't automatically what you want it to be

lucid ember
#

Well, I need it to print the voice channel the member was before he was moved

#

Is it possible ?

fast osprey
#

!d discord.AuditLogDiff

unkempt canyonBOT
#

class discord.AuditLogDiff```
Represents an audit log “change” object. A change object has dynamic attributes that depend on the type of action being done. Certain actions map to certain attributes being set.

Note that accessing an attribute that does not match the specified action will lead to an attribute error.

To get a list of attributes that have been set, you can iterate over them. To see a list of all possible attributes that could be set based on the action being done, check the documentation for [`AuditLogAction`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AuditLogAction), otherwise check the documentation below for all attributes that are possible.

iter(diff) Returns an iterator over (attribute, value) tuple of this diff.
lucid ember
#

Yeah I already seen that but I don't understand how to use it

restive flint
#
@bot.command(name="temizle")
async def clearChat(ctx, *arg):
    if not arg[0]:
        await ctx.send("İçeri bşe yazcan aq")```
#

when an arguement isn't passed with the command it crashes

naive briar
#

Remove the indexing [0]

restive flint
#

I made *arg

fast osprey
haughty summit
fast osprey
#

What is the behavior? What happens?

haughty summit
#

I show an embed after a command , it takes the 4 command and shows 4 in a row after some time, one of them with messed data from fetch

slim bloom
#

How can I make my bot create an event for this?

fast osprey
#

Code?

haughty summit
#

How could I block an user of running several commands ? Dont want to execute nothing else until prev fetch is done and the embed showed so I’d allow him to go for a new one

slate swan
#

Trying to create modmail with forums, and the dm confirmation aint sending, tried too much things, aint nothing working out. pls help me


import discord
from discord.ext import commands

class modmail(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.sessions = {}
        self.guild_id = 1233501243645755524  
        self.forum_channel_id = 1254273071309656136  

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return

        if isinstance(message.channel, discord.DMChannel):
            await self.forward_dm_to_forum(message)

    async def forward_dm_to_forum(self, message):
        guild = self.bot.get_guild(self.guild_id)
        forum_channel = guild.get_channel(self.forum_channel_id)

        if not forum_channel:
            print("Forum channel not found.")
            return

        post_title = f"{message.author.name} - {message.author.id}"
        post_content = message.content

        try:
            thread = await forum_channel.create_thread(
                name=post_title,
                message=discord.ForumMessage(content=post_content),
                auto_archive_duration=1440 
            )

            print("Post created successfully.")

            await message.author.send("Your message has been received. A moderator will respond soon.")

            await thread.send(f"**{message.author.name}:** {message.content}")

            for attachment in message.attachments:
                await thread.send(file=await attachment.to_file())
        except Exception as e:
            print(f"Error creating post: {e}")

    def is_modmail_thread(self, channel):
        return isinstance(channel, discord.Thread) and channel.parent_id == self.forum_channel_id

async def setup(bot):
    await bot.add_cog(modmail(bot))
fast osprey
haughty summit
#

Yeah sorry If I am not explaining myself really well, the issue is triggering several commands at once when it is not expected at all, also it makes several calls to the API for the fetch and it’s not expected at all either

fast osprey
#

Are you caching the responses from the API at all?

haughty summit
#

Hmmm I dont Solstice

fast osprey
lucid ember
#

Is there a way to get the date of an audit log entry?

slate swan
fast osprey
#

just let the normal error handler print out the full traceback

slate swan
fast osprey
#

but you can get an error from trying to dm someone for a number of reasons

fast osprey
unkempt canyonBOT
fast osprey
# haughty summit Hmmm I dont Solstice

This is going to be much easier to solve knowing what exactly is happening and what the expected flow is. Is the external API rate limiting you? Are you just mixing up some race condition internally?

hearty basalt
#

"actions": [discord.AutoModRuleAction(type=discord.AutoModRuleActionType.send_alert_message, channel_id=1247859469514182656)],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: AutoModRuleAction.init() got an unexpected keyword argument 'type'

what am i doing wrong 😭

fast osprey
#

What library(s) are you using?

haughty summit
hearty basalt
haughty summit
#

Can I dm you Solstice?

#

Ok

fast osprey
#

It's worth identifying what you're doing inside of a command

#

that would be impacted by something out of it

lucid ember
#

How does AuditLogEntries limit works?

haughty summit
fast osprey
#

There's really no reason to do that yourself over just using the built-in command framework, but that wouldn't cause race conditions

drifting arrow
#

okay.

#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

fast osprey
#

Consider implementing slash commands and responding ephemerally rather than dming them

haughty summit
#

why that should be avoided Solstice?

#

Just curious

fast osprey
#

DM's are annoying, invasive, very heavily rate limited and not guaranteed to work

haughty summit
void pewter
#

import discord
from discord.ext import commands
from discord import app_commands
import asyncio
import os
from dotenv import load_dotenv

Why isnt this working even tho ive done pip

haughty summit
versed basalt
#

is there any easy way to get the unicode Ids for emojis in discord?

slate swan
haughty summit
#

It seems I already managed preventing an user to send more than one command if the fetch from the prev one havent finished but my concern is what will happen when hundred users will be throwing a command and all of them tryin to pass through the check one for example

fast osprey
#

What do you think the problem will be

#

I think there's a bit of a misunderstanding how asyncio works

hybrid light
#

Is it possible to check who joined from a specific invite code? I already have people on the server and I need to check who invited them :))

wanton current
hybrid light
wanton current
#

Then you don't know

hybrid light
heady cave
#

Resources for dpy?

vapid parcel
#

Alright since the Discord Developers server isn't MUCH help. I might as well ask here.

https://discord.com/blog/feast-your-moniteyes-on-todays-exciting-developer-updates

So for this blog post or whatever right, does this only effect the bots that are Monetized/Verified? Say im doing it on a website and not doing it in discord.

I am asking this because it does state..

"Developer teams monetizing their apps on Discord will need to adopt Discord's Premium App features..."

Also if my bot is not verified am I allowed to monetize my bot that way? Because I can not monetize my bot in discord while its not verified.

We're excited to highlight some new monetization features available for developers in the US, UK, and EU to utilize, and globally purchasable by all users.

#

Yes this is not in effect yet, but it will be later on, I am just asking tho.

fast osprey
#

If you are monetizing your bot anywhere, you need to also monetize it on discord for the same price or less

vapid parcel
#

How can I monetize it when its not verified?

#

Thats why I am wondering if those rules only effect apps that are verified.

hearty basalt
#

you can't monetize it if it's not verified

vapid parcel
#

Yes but it doesn't state that anywhere in there. You just can't monetize it with discord.

#

Discord needs to update the blog to be a little more strict or explain it a little better.

hearty basalt
#

i jus watched NTTS' video on it, explained it pretty well

vapid parcel
#

Because thats just a loop right there is it not? Because technically you aren't verified and you can just monetize it on a website and be fine. Because it states "Developer teams monetizing their apps on Discord"

vapid parcel
fast osprey
#

Do not rely on youtubers to explain your legal obligations to you lol

vapid parcel
fast osprey
#

was agreeing with you

vapid parcel
#

Yeah and I was agreeing with you too xD

restive flint
#

Yo guys how do I do this for my own bot

#

!code

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

restive flint
#

I need this I want to make a yes or no type thing

wanton current
#

Embed?

restive flint
#

Yeah Is that what they are called?

wanton current
#

yes

#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
restive flint
#

This boz

#

I’ll keep that in mind thank you

#

Can I even send one myself?

wanton current
#

what do you mean

restive flint
#

Like can a user send an embed

wanton current
#

nope

#

only way if a website has an embed like https://youtube.com

restive flint
#

Ohh

#

So no alright

heady cave
vapid parcel
vapid parcel
#

Maybe im wrong.. but thats what I remember

wanton current
#

havent heard anything

vapid parcel
#

Whats even the risk behind users sending Embeds?

#

I truly don't see the issue with Users sending embeds..

#

I remember a video on YouTube, a plugin for Better Discord (3rd party app for discord which breaks ToS) that allowed a User to send Embeds, so users have the ability to send requests n stuff to do it.

#

But this was years ago.

merry cliff
#

I mean there are user apps now which can send an embed for you I guess

opal vortex
#

question is it possible to provide a custom setup_hook without subclassing Bot or AutoShardedBot? I have a use case for this as I need to have my main bot init code be inside of my own custom c extension code and I cannot use cython because it would not work well for what I need to do with the code.

quasi bough
opal vortex
quasi bough
#

yep

opal vortex
#

👌

opal vortex
#

ah I see

#

F

#

it seems the replaced setup_hook no work.

quasi bough
#

pithink There should be some errors, did you call bot.run()/bot.start()

#

setup_hook gets triggered inside them

opal vortex
#

it seems only way to make it work that way is to:

class BotSetupHook:
    def __init__(self, bot: Bot):
        self.bot: Bot = bot
        self.logged_in_: bool = False

    async def setup_hook(self) -> None:
        if self.logged_in_ is False:
            self.logged_in_ = True
            print(f'{self.bot.user.name}#{self.bot.user.discriminator} is connected!')
        try:
            await self.bot.load_extension(f'DiscordBot.cogs')
        except Exception as ex:
            traceback.print_exception(ex)
#

in a dummy class

#
async def run_bot():
    activity: Activity = await get_activity()
    client: Bot = Bot(
        command_prefix=[],
        help_command=None,
        description='',
        activity=discord.Streaming(
            name=activity.ActivityName,
            url=activity.ActivityUrl),
        intents=discord.Intents.default(),
        pm_help=False)
    hook: BotSetupHook = BotSetupHook(client)
    client.setup_hook = hook.setup_hook
    async with client:
        await start_bot(client)
quasi bough
#

why can you not subclass the Bot object though

#

and since you're using an async function to start the bot why not just do the setup_hook task inside it

opal vortex
opal vortex
#

because the start function is a blocking call when it reaches the connect after login.

#

😅

#

I did try it before and it did not work too well.

#

😭

timber dragon
#

You can assign the method to anything

#

Or use the event decorator

#

But also you could just load the extension inside run_bot

drifting arrow
#

Anybody got any ideas on how I can format this better?

drifting arrow
#

heh. figured it out

timber dragon
#

Do you really need the "Revives:" text

#

Instead of just

  • Name: 112
  • Foo: 600
    ...
#

Or

  • Name
    112
  • Foo
    69
drifting arrow
#

Ended up going with this

timber dragon
#

Now look at that on mobile lol

haughty summit
# fast osprey What do you think the problem will be

The problem is users commands requests are queuing unintentionally so it means after two users runs a command, one of them will come first and the other will need to wait for the first fetch to be completed, if we replicate this to N users it would suppose the N user getting the last to the command will need to wait to N-1 fetches to be completed

haughty summit
#

Good morning Everyone

fast osprey
haughty summit
#

No

#

Welldesign itself but not on purpose

#

I finally managed rate limit on each user so thgey can not throw several commands in a row but just one by one, so cache for users and works properly

#

the problem is this last one I mentioned

fast osprey
#

That's not something that would natively happen in asyncio unless you are choosing and designing it that way

haughty summit
#

tried adding threads so I could somehow execute the fetches in a concurrent mode since each thread would pull its data but no way

fast osprey
#

You don't need threads

haughty summit
fast osprey
#

You need to understand how asyncio works

haughty summit
#

That's okay

#

No deeply understanding but not messing when using them either

#

does not fix my problem anyways

fast osprey
#

asyncio is already doing this for you in an async framework like dpy

haughty summit
#

why in my log I then see they are not running concurrently

fast osprey
#

Like I've said, in this case you need to be going out of your way to make individual command invocations block on each other

#

What is your code

haughty summit
#

it is absolutely secuential

#

can I paste code blocks here?

#

the core ones to see the exec model?¿

fast osprey
#

Here or in a paste service if its too long

hearty basalt
#

chat wtf does this mean:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).

#

^ tryna make a TextInput

haughty summit
fast osprey
#

Not ideal

hearty basalt
#

just use pastebin

fast osprey
haughty summit
# fast osprey Not ideal

on_message handler - 1

async def on_message(message):
    
    
    if message.author == client.user:
        return
    command = message.content.split()

    if isinstance(message.channel, discord.DMChannel):
        
        guild = client.get_guild(SERVER_ID)
        
        if guild:
            member = guild.get_member(message.author.id)

        # Use asyncio.create_task to handle commands without blocking
        asyncio.create_task(handle_commands(message, guild, member)) 
#

2

    if member:
        role = discord.utils.get(guild.roles, name="orion_access")
        if role in member.roles:
            if message.content.startswith(('/check', '/trades', '/holdings', '/tokenbywallet', '/solscan')):
                asyncio.create_task(handle_command_with_queue(message))
            else:
                await message.author.send("Command not valid: /check opt[1D/7D/30D] wallet_Address")
        else:
            await message.author.send("Your subscription has run out, renew to continue using the bot.")
    else:
        await message.author.send("Your subscription has run out, renew to continue using the bot.")

#

3

    user_id = message.author.id

    async with command_queue_lock:
        if user_id in command_queue:
            await message.author.send("Please wait for your previous request to complete.")
            return

        command = message.content.split()
        command_queue[user_id] = command

    try:
        await handle_command(message)

    finally:
        async with command_queue_lock:
            if user_id in command_queue:
                del command_queue[user_id]
fast osprey
#

You have a lock right there

#

You put that in intentionally

#

Also lots of unneeded asyncio.create_tasks

haughty summit
#

let me paste last ones please

#

4

#
    async with cooldown_lock:
        if message.author.id in cooldowns and cooldowns[message.author.id] > datetime.now():
            await message.author.send("Slow down, you are going too fast. Wait and try again.")
            return

        log(f"{message.author} used command: {message.content}")

        cooldown_time = random.randint(2, 4)
        cooldowns[message.author.id] = datetime.now() + timedelta(seconds=cooldown_time)

        command = message.content.split()
        
        if message.content.startswith('/check'):
            await handle_check_command(message, command) ```
#

5 - Last command processing function, the desired behaviour would be executing this one in parallel by different users so they do not need to wait for a fetch from the previous one to be completed .

    if len(command) > 1 and (len(command[1]) == 44 or len(command[1]) == 43):
        wallet_address = command[1]
        valid_count = await get_trans_count(wallet_address)
        temp_message = await message.channel.send("Fetching wallet information, please wait...")
        try:
            if valid_count == False:
                await message.author.send(f"**This wallet has too many transactions.**  ** (Mev Wallet 💀) ** ** Try checking a different wallet. **")
            else:
                tokens1D, tokens7D, tokens30D, metrics_1D, metrics_7D, metrics_30D, tokens_holded, solana_price, solana_balance, solana_balance_USD, Inflows, Outflows = await fetch_data(wallet_address)
                
                if metrics_1D[0]['TokensTraded'] == 0 and metrics_7D[0]['TokensTraded'] == 0 and metrics_30D[0]['TokensTraded'] == 0:
                    await message.author.send(f"No relevant activity detected on this wallet, recommended digging deeper on : https://solscan.io/account/{wallet_address}")
                else:
                    embed = createEmbed(metrics_1D, metrics_7D, metrics_30D, tokens30D, wallet_address, solana_balance, solana_price, solana_balance_USD)
                    await message.author.send(embed=embed)
        except Exception as e:
            tb = traceback.format_exc()
            await message.author.send(f"Error occurred !! ")
            print(f"Error occurred: {e}  \n\nTraceback:\n{tb}")
        finally:
            await temp_message.delete()
    else:
        await message.author.send("Address not valid") ```
haughty summit
fast osprey
#

They do

#

You're just throwing locks into it for some reason

#

Every time on_message fires, that is already its own task

#

If 5 messages come in on the same second, that is 5 tasks scheduled in asyncio running "concurrently"

haughty summit
#

The log does not show that Solstice . . .

fast osprey
#

Because. You're. Locking.

#

You are doing this to yourself actively

#

If you don't believe me, make a minimal bot with just an on message that sleeps and does something. No locks

haughty summit
#

I do believe you man, of course

#

but weird as I am coming from that model and I didnt feel it was working

#

I easily see in the log users requests and also when the fetch starts

#

so I never saw the fetch to go in parallel for just 2 users

fast osprey
#

I'm not sure how you got into a state where you added locks to your code while then also struggling with your code locking. You need to strip this all away and add things on intentionally

#

This is like locking your front door and then coming to someone and asking why you can't get into your house

haughty summit
#

would you get rid of the create tasks as well?

fast osprey
#

Yes, until you understand the case where you'd need it

#

You can just await async calls

haughty summit
#

so

#

Just to understandaccording to the draw I shared yesterday and looking at the code, you would get rid of create-tasks and locks and you are completely sure the fetch_data could be executed in parallel by several users as triggered thread from on_message for each message received

fast osprey
#

I don't know what you want. You should stop and understand what locks and tasks are, and how the library works barebones before you proceed

haughty summit
#

it was not my question but okay

#

I may have explained 10 times already since posting in this channel yesterday

fast osprey
#

I'm not going to solve this for you given how obtuse the use case is. I'm going to explain to you how the individual pieces work so you can put them together. If you want to wait for someone else to do that for you that's okay too

#

But my strong advice is to remove all of the locks and create_tasks and layer them in as needed once you understand what they're doing

haughty summit
#

I dont want anyone to solve this for me but just get help for the execution model and the approach I try to follow, you answer one question good and next question your reply is I do not know what you want to do

#

but okay, appreciated, thank you in advance

fast osprey
#

It's important for you to step back and learn the basics of asyncio and understand what is happening when a discord event fires. I can summarize it for you but this will work best if you do some minimal exercises

haughty summit
fast osprey
#

There's an interactive tutorial somewhere that never got finished but covers the basics

haughty summit
#

Thank you so much Solstice, I will def take a look

fast osprey
#

#async-and-concurrency would be a good spot to ask detailed questions. Libraries like dpy build on top of these concepts as base knowledge

#

But the short of it is that dpy creates a new task to handle any event it sees. These tasks will inherently be independent of each other unless you tie them together with things like locks

toxic breach
#

How can I make some bot.tree.commands be shown only to some roles?

lucid ember
#
    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_move):
        if entry.user.id in moderators:
            date = f"{entry.created_at.day}.{entry.created_at.month}.{entry.created_at.year} | {entry.created_at.hour}.{entry.created_at.min}"
            print(f"Moderator: {entry.user}\nBefore: {entry.before}\nAfter: {entry.after}\nDate: {date}")
            amountOfMoves = amountOfMoves + 1```


Any idea why "entry.before" and "entry.after" prints as "AuditLogDiff" and not the voice channel the user was in before and after?
fast osprey
fast osprey
fast osprey
#

Like you use any object. Access its attributes and print whatever you'd like in whatever format you want

lucid ember
#

It's attributes don't have any info it them

fast osprey
#

And how are you determining that?

lucid ember
fast osprey
#

Don't trust your IDE, they lie pretty often

lucid ember
#

Mhm

#

I need to see which voice channel the member was moved from

thorn smelt
#

Hi

lucid ember
#

Which option would I need to input?

thorn smelt
#

İs here general chat?

haughty summit
fast osprey
unkempt canyonBOT
#

A member’s voice channel has been updated. This triggers when a member is moved to a different voice channel.

When this is the action, the type of extra is set to an unspecified proxy object with two attributes:

channel: A TextChannel or Object with the channel ID where the members were moved.

count: An integer specifying how many members were moved.

New in version 1.3.

fast osprey
lucid ember
#

It only shows the before or the after

#

Is it possible to configure that?

fast osprey
#

The audit log may not record where they were in. It's telling you how to access which channel they were moved to

lucid ember
fast osprey
#

Look at your variable called Bot and what you're doing with it

pulsar lintel
#

ok thx

lucid ember
#

date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"

How can I only get the "day" without anything else?

Right now it prints the exact time and date:
2024-06-24 16:20

I want it to only get the "24"

#

I tried searching the docs but it's pretty messy

hearty basalt
#

you could index it but theres prob a better way

hushed galleon
hushed galleon
#

well .created_at in dpy usually is a datetime object

#

not to mention your astimezone() call is working, and thats a method datetime objects provide

lucid ember
#

Oh

hushed galleon
lucid ember
#

I just tried using .day and it worked.
Seems that I just misplaced it at first and thus I didn't see the actual expected results

lucid ember
#

like,

if entry.created_at.day != 24 then: return```
#

Something like that

#

Anyways, you solved my issue here so thank you!

hushed galleon
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.

You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to do this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
lucid ember
#

BRUHHHHHHHHH

#

Why did I not think of thatttt

hushed galleon
#

lol

lucid ember
#

Well anyways it works now so who cares I guess

hushed galleon
#

not sure what the ratelimits are on retrieving audit logs, but overtime your bot will have to make more API requests if there are a bunch of logs from the 24th to whatever day it is in the future

opal vortex
lucid ember
#
    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_move):

        day = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem')).day}"
        date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"
        
        if entry.user.id in moderators:
            
            if day != wantedDay:
                None
                
            elif day == wantedDay:

                print(f"Moderator: {entry.user}\nMoved Someone To: {entry.extra.channel}\nAmount Of Users: {entry.extra.count}\nDate: {date}\n---------------------------------")
                amountOfMoves += entry.extra.count

    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_disconnect):

        day = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem')).day}"
        date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"
    
        if entry.user.id in moderators: 
            if day != wantedDay:
                None
            elif day == wantedDay:   
                print(f"Moderator: {entry.user}\nDate: {date}\n---------------------------------")
                amountOfDisconnects += entry.extra.count


    print(f"Moves: {amountOfMoves}\nDisconnects: {amountOfDisconnects}\nRoles: {amountOfRoles}")```


The bot ignores everything after the first - `async for entry`, any idea why that happens?
hearty basalt
#

what's the maximum amount of buttons one message can have?

fast osprey
#

5 rows of 5

hearty basalt
#

thanks!

slate swan
#

!intents

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.

slate swan
#

chat, i was making the ai bot and uh, i got an error

wanton current
#

your json is not json

slate swan
wanton current
#

try printing the json and see what it says

slate swan
#

maybe there's something wrong

wanton current
#

print the response and see if there's any error

slate swan
#
print(response.text)```
?
#

got it

#

(its so fucking large)

#
<!DOCTYPE html><html lang="en"><head><meta charSet="utf-8"/><title>landing.meta.title</title><meta name="title" content="landing.meta.title"/><meta name="description" content="landing.meta.description"/><meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no;user-scalable=0, maximum-scale=1;"/><link rel="icon" href="/favicon.ico" type="image/x-icon"/><link rel="icon" href="/favicon-16.png" sizes="16x16"/><link rel="icon" href="/favicon-32.png" sizes="32x32"/><link rel="icon" href="/favicon-76.png" sizes="76x76"/><link rel="manifest" href="/manifest.webmanifest"/><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"/><link rel="mask-icon" href="/safari-pinned-tab.svg" color="#D3FD7A"/><meta name="msapplication-config" content="IEconfig.xml"/><meta name="yandex-verification" content="eee3a502662b0219"/><meta property="og:locale" content="undefined"/><meta property="og:type" content="website"/><meta property="og:url" content="https://fusionbrain.ai"/><meta property="og:title" content="landing.meta.title"/><meta property="og:description" content="landing.meta.description"/><meta property="og:image" content="https://fusionbrain.ai/static/fusion/undefined/assets/images/ogimage.png"/><meta property="twitter:card" content="summary_large_image"/><meta property="twitter:url" content="https://fusionbrain.ai"/><meta property="twitter:title" content="landing.meta.title"/><meta property="twitter:description" content="landing.meta.description"/><meta property="twitter:image" content="https://fusionbrain.ai/static/fusion/undefined/assets/images/ogimage.png"/><meta name="next-head-count" content="25"/><link rel="preload" href="/_next/static/media/a9a5d0e267ec69c0-s.p.woff2" as="font" type="font/woff2" crossorigin="anonymous" data-next-font="size-adjust"/><link rel="preload" href="/_next/static/media/c6895e2f3f2f01a1-s.p.woff2" as="font" type="font/woff2" crossorigin="anonymous" data-next-font="size-adjust"/><link rel="preload" href="/_next/static/media/e242388265416af6-s.p.woff2" as="font" type="font/woff2" crossorigin="anonymous" data-next-font="size-adjust"/><link rel="preload" href="/_next/static/css/9d8761c53a5eb1d9.css" as="style"/><link rel="stylesheet" href="/_next/static/css/9d8761c53a5eb1d9.css" data-n-g=""/><noscript data-n-css=""></noscript><script defer="" nomodule="" src="/_next/static/chunks/polyfills-c67a75d1b6f99dc8.js"></script><script src="/_next/static/chunks/webpack-0ec2c4232030ab0c.js" defer=""></script><script src="/_next/static/chunks/framework-ce84985cd166733a.js" defer=""></script><script src="/_next/static/chunks/main-897546ac9d6aa7fa.js" defer=""></script><script src="/_next/static/chunks/pages/_app-2353887ca91e4a6e.js" defer=""></script><script src="/_next/static/chunks/pages/auth/signin-1e211d68d2777ea2.js" defer=""></script><script src="/_next/static/z0AA4TPRZ_reA1mEO8ycK/_buildManifest.js" defer=""></script><script src="/_next/static/z0AA4TPRZ_reA1mEO8ycK/_ssgManifest.js" defer=""></script></head><body><div id="__next"><div id="app-container" class="__variable_1cea59 __variable_4c798b"><div id="portals"></div><noscript><div><img src="https://mc.yandex.ru/watch/91316918" style="position:absolute; left:-9999px;" alt="" /></div></noscript><!--$--><!--/$--></div></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"providers":{"keycloak":{"id":"keycloak","name":"Keycloak","type":"oauth","signinUrl":"https://fusionbrain.ai/api/auth/signin/keycloak","callbackUrl":"https://fusionbrain.ai/api/auth/callback/keycloak"}}},"__N_SSP":true},"page":"/auth/signin","query":{"callbackUrl":"https://fusionbrain.ai/keys/"},"buildId":"z0AA4TPRZ_reA1mEO8ycK","isFallback":false,"gssp":true,"locale":"ru","locales":["ru","en"],"defaultLocale":"ru","scriptLoader":[]}</script></body></html>

like what the fuck 😭🙏

wanton current
#

that's an html page

slate swan
#

...oh

#
import discord
from discord.ext import commands
import requests
from discord import Intents
import json


DISCORD_TOKEN = 'token'


FUSION_BRAIN_API_KEY = 'api_key'


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

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

@bot.command()
async def generate(ctx, *, prompt: str):
    
    api_url = 'https://fusionbrain.ai/keys/'

    
    headers = {
        'Authorization': f'Bearer {FUSION_BRAIN_API_KEY}',
        'Content-Type': 'application/json'
    }

    
    data = {
        'prompt': prompt
    }

    
    response = requests.post(api_url, json=data, headers=headers)

    if response.status_code == 200:
        try:
            
            json_response = response.json()
            
            image_url = json_response.get('image_url')
            if image_url:
                await ctx.send(image_url)
            else:
                await ctx.send("Failed to generate image.")
        except json.JSONDecodeError:
            await ctx.send("Invalid JSON response from the image generation service.")
            print(response.text)
    else:
        await ctx.send("Error contacting the image generation service.")


bot.run(DISCORD_TOKEN)```
something in code is broken i think
wanton current
#

are you making a request to the right url

slate swan
#

i have stupid question

slate swan
#
await ctx.author.edit(nick="idk")

whats wrong with this

#

it keep not working for some reason

#

bot i admin btw

slate swan
#

well, it doesn't print any error

slate swan
#

bruh 💀

wanton current
slate swan
#

if you mean a log for error

wanton current
#

are you starting your bot with bot.run?

slate swan
#

ye ofc bot works

#

in fact i can change the role name but not username nickname

#

ok i think the action is forbidden but the bot has admin ??

#

is it bc of intents?

#

what is happening im losing it 😫

wanton current
#

is the bot role above the role of the member you're trying to edit the nickname of?

slate swan
#

well, where do i put the api key

slate swan
#

but idk how that is related

wanton current
#

you can't edit the nickname of someone whose top-role is above yours

slate swan
#

as the bot is changing the nickname of the username it got nothing to do with the role

wanton current
#

Yeah, then that's the reason

slate swan
#

also im changing my nickname through command

slate swan
wanton current
#

The bot can't edit your nickname if you're the owner

slate swan
#

oh i see

#

but it can edit others right?

#

yeah

wanton current
#

Yeah, if the bot's top-role is higher than their top-role

slate swan
#

is there a way i can bypass this obstacle for the owner

wanton current
#

no

slate swan
#

😔

wanton current
wanton current
#

I'm not familiar with this service so can't really help you further

boreal sigil
odd cairn
#

help guys i need to make myself admin without commands

#

i got termed and lost my server

shrewd apex
#

huh?

#

not much u can do I am afraid

fast osprey
#

contact discord support

vapid parcel
#

Does anyone know how to transfer 1 postgres db thats in a docker to another host? But without losing the data in it..?

#

Just needing docs or something on it?

#

Wrong channel mb

pale zenith
#

Oh shit ur right

lucid ember
#
    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_move):

        day = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem')).day}"
        date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"
        
        if entry.user.id in moderators:
            
            if day != wantedDay:
                None
                
            elif day == wantedDay:

                print(f"Moderator: {entry.user}\nMoved Someone To: {entry.extra.channel}\nAmount Of Users: {entry.extra.count}\nDate: {date}\n---------------------------------")
                amountOfMoves += entry.extra.count

    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_disconnect):

        day = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem')).day}"
        date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"
    
        if entry.user.id in moderators: 
            if day != wantedDay:
                None
            elif day == wantedDay:   
                print(f"Moderator: {entry.user}\nDate: {date}\n---------------------------------")
                amountOfDisconnects += entry.extra.count


    print(f"Moves: {amountOfMoves}\nDisconnects: {amountOfDisconnects}\nRoles: {amountOfRoles}")```


The bot ignores everything after the first - `async for entry`, any idea why that happens?
fast osprey
#

You may wish to do a little debugging and see what your call to audit_logs is returning

lucid ember
#

Any idea why entry.target.is_timed_out() prints out this error: 'User' object has no attribute 'is_timed_out'?

fast osprey
#

Because User objects aren't tied to a guild and can't be timed out

lucid ember
#

By the way, entry.user.id prints as NoneType

#

But only when I check the member_role_update

#

It works fine for anything else

turbid shard
#

hi

#

anyone awake?!

#

i'm trying to run 2 tasks at once, flask and the discord bot
how can i do this?

def flask():
    uvicorn.run(app, host='127.0.0.1', port=5000)
if __name__ == '__main__':
    threading.Thread(target=flask).start()
    bot.run('')```
I tried doing this, however the flask app just breaks lol
can anyone help me?
fast osprey
#

I would recommend not doing these in the same process anyways

toxic breach
#

!d ctx.reply

#

!d await ctx.reply

hushed galleon
#

!d discord.ext.commands.Context.reply

unkempt canyonBOT
#

await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shortcut method to [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) referenced by this context.

For interaction based contexts, this is the same as [`send()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.send).

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
toxic breach
#

how can i make a ctx.reply, not mention the member?

hushed galleon
#

as for that, you'd pass mention_author=False

toxic breach
#

thank you mate

toxic breach
#

How can I make some bot.tree.commands be shown only to some roles?

#

using @bot.tree.command()

hushed galleon
toxic breach
#

oh

hushed galleon
#

well technically a bot can make an API request to change it if they have an oauth bearer token with applications.commands.permissions.update scope, but discord.py can't perform an oauth flow to get one

toxic breach
#

so I have to make it by hand? cant I make it somehow like py @commands.has.any_roles[ROLE'S IDS HERE]

hushed galleon
#

there is a non-native check built into discord.py for that

#

!d discord.app_commands.checks.has_any_role

unkempt canyonBOT
#

@discord.app_commands.checks.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.checks.has_role), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingAnyRole) if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).

New in version 2.0.

Note

This is different from the permission system that Discord provides for application commands. This is done entirely locally in the program rather than being handled by Discord.
hushed galleon
#

but it won't be able to hide your slash commands from users unlike the native permissions

toxic breach
#

with

#

!d discord.app_commands.checks.has_permissions

unkempt canyonBOT
#

@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions).

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).

New in version 2.0...
toxic breach
#

?

hushed galleon
#

for permissions you can set native default permissions

#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
toxic breach
#

hm okayy, thx for your help Bear3_thxheart

hushed galleon
#

users won't see your command without those by default, but the admin can still apply member/role/channel overrides in the integrations tab to bypass it

shy eagle
#

yo

#
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

getting this error when after clearing messages it doesnt respond to my slash command

fast osprey
#

You have to respond within 3 seconds

slate swan
#

any reason to this? ive had this problem before and never got a fix

fast osprey
#

Code?

shy eagle
#

!paste

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

shy eagle
#

anything wrong with this

fast osprey
#

You can't followup before responding

turbid shard
#
                  ^^^^^^^^^^
AttributeError: 'str' object has no attribute 'author'```
#

why can't i do this anymore 😭

patent hull
#

Read the error

lucid ember
#
    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_move):

        day = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem')).day}"
        date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"
        
        if entry.user.id in moderators:
            
            if day != wantedDay:
                None
                
            elif day == wantedDay:

                print(f"Moderator: {entry.user}\nMoved Someone To: {entry.extra.channel}\nAmount Of Users: {entry.extra.count}\nDate: {date}\n---------------------------------")
                amountOfMoves += entry.extra.count

    async for entry in guild.audit_logs(limit=None,action=discord.AuditLogAction.member_disconnect):

        day = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem')).day}"
        date = f"{entry.created_at.astimezone(tz=pytz.timezone('Asia/Jerusalem'))}"
    
        if entry.user.id in moderators: 
            if day != wantedDay:
                None
            elif day == wantedDay:   
                print(f"Moderator: {entry.user}\nDate: {date}\n---------------------------------")
                amountOfDisconnects += entry.extra.count


    print(f"Moves: {amountOfMoves}\nDisconnects: {amountOfDisconnects}\nRoles: {amountOfRoles}")```


The bot ignores everything after the first - `async for entry`, any idea why that happens?
upbeat otter
upbeat otter
#

show relevant code

fast osprey
#

You also have no logging, no way to tell what's "being ignored" as most of your code would just silently run anyways

lucid ember
lucid ember
fast osprey
#

Code doesn't get "ignored"

#

Either you are not executing it because of how for loops work, or you are and it just isn't doing what you expect. You need to do some debugging to figure out which. We aren't python interpreters

lucid ember
fast osprey
midnight oracle
#

In case it takes more than 3s to respond, Discord will wait for it to finish

#

Any other error besides that one?

copper flume
#

how do I reduce my bot's load? Like i don't wanna cache any guild where the bot is not used

patent hull
#

Wdym not used

wanton current
#

you can turn off guild chunking at startup and chunk guilds when you need it

midnight oracle
hushed galleon
#

i dont think turning off the member cache/chunking at startup affects overall response times, unless you specifically mean with commands/events that would benefit from member caching

copper flume
copper flume
# patent hull Wdym not used

After my bot has restarted if anyone is not using any command or event is not being triggered then it means it is a dead server so it is useless to cache the whole guild for no reason as it uses unnecessary ram

vapid parcel
#

Does anyone know if you can get a testing verified bot..? For sku purpose only tho. or have a bot that has skus that isn't verified?
Because I rather do everything on a testing bot before on my actual bot if that makes sense.

drifting arrow
#

Is it possible for a discord bot to manage the guilds integrations?

#

Specifically the section that controls the commands

merry cliff
#

I mean they can make webhooks

#

but I don't think bots can add other bots

drifting arrow
#

Adding bots is not what I want. I want to be able to make a command visible to only specific people and roles

merry cliff
#

oh

drifting arrow
#

it's a slash command

#

So unless there's a better way that messing with the bots integrations or having it check if they're in a list of discord ids..

merry cliff
#

perhaps @app_commands.default_permissions()?

fringe wharf
#

can someone help, its probably something so simple that im missing but my command isnt showing. I can share the code but would prefer to share it via dm if thats ok?

fringe wharf
drifting arrow
#

Are you syncing your commands to the server?

vapid parcel
#

So how am I gonna be "Already subscribed" to it. But not be subscribed to it?

#

How do I even fix this issue...?

drifting arrow
#

:/

vapid parcel
#

I don't understand discord bro :/

#

so I had to go on an alt and actually buy it

#

cuz I couldn't get rid of the bug

#

which is kinda sad... but its fine.

wary shore
#

i'm getting this weird error in my discord bot and idky

#

this is the source code:

from discord.ext import commands, tasks
import discord
from dotenv import dotenv_values
import time

import feedparser

client = discord.Client(intents=discord.Intents.all())
config = dotenv_values('.env')
token = config['TOKEN']
current_events_channel = 1253383848654536774
congressional_bills_channel = 1254766638897565726
posted_articles = []

async def extract_news(domain, channel_id):
    fox_parser = feedparser.parse(domain)

    for entry in fox_parser['entries']:
        if (not entry['id'] in posted_articles) and \
        int(time.asctime().split(' ')[3].split(':')[0]) == entry['published_parsed'][3] - 4 and \
        int(time.asctime().split(' ')[3].split(':')[1]) == entry['published_parsed'][4]:
            await client.wait_until_ready()
            channel = client.get_channel(channel_id)
            await channel.send(f'''# {entry['title']}
{entry['link']}''')

            posted_articles.append(entry['id'])


@tasks.loop(seconds=1)
async def checkForCurrentEvents():
    await extract_news('https://moxie.foxnews.com/google-publisher/politics.xml', current_events_channel)
    await extract_news('https://www.govinfo.gov/rss/bills.xml', congressional_bills_channel)


@client.event
async def on_ready():
    print('Ready for action')
    await checkForCurrentEvents.start()


client.run(token)
fast osprey
#

Whatever feedparser is, it's blocking. Also don't use on_ready for things you want to happen once

sinful galleon
#

I'm setting up a booster embed that gets sent once someone boosts the server. I've seen that the mimu bot is able to recognieze when a server has been boosted but Idk how to code that myself.

#

I asked chat gpt and it came up with this
@bot.event
async def on_member_update(before: Member, after: Member):
if before.premium_since is None and after.premium_since is not None:
channel = after.guild.get_channel(GENERAL_CHANNEL_ID)
if channel is not None:
embed = create_boost_embed(after.guild)
await channel.send(f"You're a star for supporting the server, {after.mention} StarBlush0")
await channel.send(embed=embed)
else:
print("Channel not found")
else:
print("No boost change detected")

fast osprey
#

There is not a reliable way of detecting this. That bot is making guesses

merry cliff
#

you could check for the message discord sends when someone boosts

#

that specific message type

fast osprey
#

(Which relies on a) the guild enabling that and b) the bot having read permissions where it's sent)

merry cliff
#

yeah

#

what about checking for the nitro booster role?

#

you could check for that role with on_member_update

sinful galleon
fast osprey
#

That does not fire for subsequent boosts

merry cliff
#

ah ok

fast osprey
#

This is why discord already has a built in way for guilds to opt in to announcing boosts

#

Anything you build on top of that is going to be less reliable

sinful galleon
fast osprey
#

It's not doing it reliably. It is guessing