#discord-bots
1 messages · Page 374 of 1
also you should not be using requests in an async application or you're going to freeze your whole bot
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
What would you guys say
what the best free website that keeps your discord bot on 24/7?
!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.
the first sentence o_ob
example: commands.Bot(..., max_messages=9000, ...)
okay
can i edit it on runtime?
like using jishaku
not officially, the limit is already set when you initialize the bot
okay
Hey folks
Are there any popular open source Discord bots that query and display information related to Steam game servers?
i saw CS2 discord bot one but its written in Java
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
in theory the one I made is standard across any game supporting steam query
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
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
huh? 🗿
Do you have to pip install all Imports?
what imports?
Just run
pip install -U discord.py
And youll get it working
Okay
So will all this work?
yes
Thanks
sorry for the late response. that's actually the module I used. It's great
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
ask in #editors-ides
i need some help with website scraping and decryption and encryption can someone help?
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)
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)
- The
guildsintent is already enabled in.default()so you can remove the line enabling it - For prefix commands you need the
message_contentintent and notmessages(it's also already in thedefault()intents - If you enable all intents, you can just go for
discord.Intents.all()already
You almost certainly don't need all intents
Hello, how should I correctly check the inverter of member who joins
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.
Not hating but uh, doesn't this just improve raid bots and nuking bots or whatever?
There was no reason for dpy adding this...
Blame Discord, not discord.py
They're merely implementing what Discord allows to cover the entire API - just like other libraries
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.
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
is this or add a for loop lol. it changes nothing
you'll get rate limited if you ban 200 peope in a for loop really quickly
proxies?
Rate limited tho
Yeah but still
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?
also, raids aren't a problem if you manage your server correctly lmao
Token loggers.
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
How do you even manage to download a token logger in the first place
Well actually here ill give an example that just happened the other day xD
guys I want to learn
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.
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
But if you actually see where the url takes you, its a discord url, so its kinda obvi its a token logger
Yeah, that's a scam that's been around for years
Im more so hating discord xD
Well yeah, but people are stupid.
there are bunch of discord API wrappers out there, choose one and look at their documentation and some guides/examples
that's what it comes down to
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
but most api wrappers heavily depend on OOP. So you need a pretty good understanding of it before you dive in
Most people get token logged cuz they think "oh its open source I can't get token logged right?"
Hi jiggly
good morning
How you been? Haven't seen you in like 5 minutes.
I have been
yo thats wild
fr
thats crazy bro
how have you been
just do
yo thats wild
yeah ik
crazy shit
ikr bro
farewell
there's a github repo that gives you fresh and alive proxies.
only god nows what those proxies are being used for
whats the difference between async def and normal def
async doesn't stop the entire program and you can run multiple functions at the same time
yeah. but there's a difference
async doesn't run on multiple threads
is the context. gives you information about the action was done
like can't I call it something else?
yes, its only a parameter.
but thats the convention
oh okay
but its weird to name the context param "dasoikjdoiasjdoi"
and makes harder development
yeah
but like discord api is weird
it takes the function name as the command itself
yeah, makes more easier writing commands and more understandable
but like how do I make it understand when its lowercase too?
oh. well thats not good lmao. So yeah ig.
I don't get it?
idk its just bad things
like for example if I make a function called hello would it understand even if it was !HELLO
That's only if you don't set the name in the command decorator.
If you put the name of the command in the decorator you can call the function with another name
if you don't want to be named as the function do this:
@bot.command(name="hi")
async def this_isnt_the_name(ctx):
...
what the hell is a decorator
@bot.command(name="hi") # <-- this
async def this_isnt_the_name(ctx):
...
It's basic Python lol
do I add the command like
@bot.command(name="hi", commands=blabla) # <-- this
async def this_isnt_the_name(ctx):
...```
nop
you just invented a parameter named commands lol
no
yes
commands is the module you imported via from discord.ext import commands
thats auto complete for discord.ext.commands
by doing this
but without commands
read the documentation...
It depends on what you are looking for.
If you're looking for more information on how to create prefix commands, check out this section:
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.command
or you can see examples in the discord.py repository
it's a decorator
no like then why do we do @bot.command instead of @command?
isn't the bot already the same
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)
can my_command be a function?
because the documentation gave limited information
what would it be otherwise
It says usually
wtf does usually mean bro its a fucking code
does it decide on its own wtf
ty but my brain is fucked psl
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
Basically everyone uses the decorator since it's easier and cleaner
tf does manually mean???
bot.add_command
no like I understand that but is there another way or sum?
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
so it just adds every single function that is underneath the @bot.command()?
no it adds the function below
only below?
@bot.command()
async def abc(ctx):
pass
@bot.command()
async def xyz(ctx):
pass
``` two different commands
search decorators on youtube
python decorators
nah I got what decorators are
functions that returns shit
like return bot.add_command()
nop 😭
remember that a decorator takes the function and adds additional functions to it, but does not modify it directly.
WHAT
a decorator completly overrides a function
its like just multiple functions at once???
and can do multiple things with that function it got, like in this case use it to register a command
I recommend that you first learn Python concepts before developing a discord bot.
Hey, any idea why this isn't working?
so like instead of doing egfunction(anotherfunction())
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?
lol, when i started people told me the same. now i can write print("hello world")
this is how I learn
what is happening?
I'm trying to make a system that scans the entire server's channels and if the channel is a textchannel it will print 1
and if not it will not respond ofc
this is what the @bot.command decorator does internally:
self.add_command is the same as bot.add_command
use isinstance in that if
if isinstance(chanel.type, discord.TextChannel):
...
isinstance(channel, discord.TextChannel)
yep
Still isn't working
do this
or you need to do isinstance(channel.type, discord.ChannelType.TextChannel
the former is just easier though
I was using discord.TextChannel instead of discord.ChannelType.TextChannel
Thank you
you know better this api than your birthday date
lol
I didn't understand shit in the documentation about @event tho
😔
pls help
@fast osprey stop lurking
(I just learned about self yesterday)
What's the actual question?
thank you
plus what the fuck does this do
@event
it registers a callback for when that event happens
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
so like on_ready is a built in event?
basically it makes it so when you run !command it runs that function
if anyone has idea, if its even possible please lmkk
use a magic wand (i'm funny)
but is like on_ready an already built in function or not?
id need an actual answer
yeah, it's a function that you can overwrite and add your own functionality to
but if I don't want to overwrite it I do @bot.listen ?
thats abstraction
Well, it does nothing by default, literally
async def on_ready(self):
pass
are you answering me?
yep
something that doesn't have a functionallity and you have to give it one
🤨
capitalism
that just made me question 4 years of learning python right there
so what does it exactly do? so @bot.event can overwrite an already-made function while @bot.listen?
like what is the difference between
bot.listen registers a callback to run in addition to the default implementation
they effectively "stack"
@bot.event()
async def on_ready():
print("Bot Is Ready.")
print("-------------")
@bot.listen()
async def on_ready():
print("Bot Is Ready.")
print("-------------")
like adding a function?
not really?
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?
Not "at once" with how asyncio works
like in an order
but thats the main point right?
like it runs both of them
yeah but not at the exact same time
wait, what!?
yeah I got it
"my whole life has been a lie" ahh reaction
wtf does this do *
in discord.py or python
python
depends if it's *args or *, args
@bot.event
async def on_ready():
print("Bot Is Ready.")
print("-------------")
@bot.listen('on_ready')
async def another_on_ready():
print("Another handler for Bot Is Ready.")
print("-------------")
you can do something like this
accepts multiple arguments in one
thanks
ok figured that out
how do I know which channel a person sends message to?
message.channel
like the text in the message
message.content is a string
could really figure this out yourself yk
!d discord.Message
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.
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
You need message content intents to see message content, yes
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
you do channel.edit
You can also pass overwrites on creation
what are intents
oh didnt see they created a channel
wtf help me
Didn't let me
telling discord what information you want
okay ty
eg. if you want content, enable Intents.message_content
So uh, any idea?
You were answered
^
You can also pass overwrites into create_text_channel
!intents
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.
I literally said that I tried but it didn't work
And it shouldn't matter if I use channel.edit or use the channel as a variable to edit it
updating an attribute in your python program won't automatically send an api request to Discord to edit it
"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
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...
WHAT THE HELL IS CLIENT
Maybe it is because I'm using 1.7.0 version?
A very unsupported version
Yeah I know, but is this the issue?
No
It has always supported passing overwrites, as can be seen in the documentation, you're likely relying on bad intellisense
This worked, but didn't actually pass the overwrites
await
oh s
how do I make the bot send a message in a specific channel?
The documentation will tell you it's a coroutine, but again, a waste of ratelimits since creation supports them
I am going to cry
I could make this only
it's an attribute, not a method
await channel.send()
Remove parentheses from @bot.event decorator
PLEASE i am dying
how the fuck do i send image (not file) thro webhook with py
an image is just a file
WHAT IS THE MESSAGE
@bot.event
async def on_message(message):
channel = message.channel
text = message()```
IS TEXT THE MESSAGE?
should work if you add a file extension like .png or .jpeg
what are you doing
I AM TRYING TO DETECT WHAT A PERSON HAS SENT
how are you sending it because an image isn't 10 bytes
I AM TRYING TO MAKE IT SO THAT WHEN SOMEONE SAYS HELLO WE SAY GREETINGS
it has like 5 pixels
i told u to use this
pls help
and idk
how are you sending it still?
it opens fine lol
i managed to broke it in every way, a sec please
@restive flint
data = {
"username": "Powiadomienie",
"content": "test",
}
files = {
'file': ('darek.png','image/png')
}
requests.post(url, data = data, files = files)```
when i click on it, it opens the image
bro even you can help I am a beginner pls answr
am asking about my own issue.
this one
i dont even do discord bots bro
oh wait I remember now
Is there a setting that will prevent this from appearing when a new person joins a server?
so can anyone PLEASE tell me am I doing this right?
no
that is hella stupid
if needs is an Intents object, yes.
yes
Example:
@bot.event
async def on_message(message: Message):
channel = message.channel
if message.content.startswith("!Hello"):
await channel.send(f"Hello {message.author.mention}")
RuntimeError: Event loop is closed
what does that f do
whats this
send entire error
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x0000025866839670>
Traceback (most recent call last):
If you send a message that contains "!Hello", the bot responds to that message.
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.
ok got it
I managed to make it to work
first discord bot ever smh
the command isn't working
,
WHY
a lil help?
how are you running it
you know any reasons?
idk
try to remove the name= and use it with >explainUses
wtf is wrong with my code?
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
because you're overriding the default functionality which is checking for commands, alternatively you can run bot.process.commands() in your on_message
do I need to call it?
yes we do call it
thank you I'll be taking my leave for today
I really appreciate the help
no worries
cant understand damn shit
Need some discord bot help, ping me if you can. I got some payment for you.
#1254209061608489051 smnn pls
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
all instance methods in a class should have self as their first parameter, including cog classes too
🤦
thx
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
guys what are guilds?
- API terminology for a discord server.
- Some dumb new feature discord is adding that adds a badge next to your name.
fr why would they call it the same thing
wait what badge?
What does it do?
aight thanks
np
wtf are they doing this is so confusing
exactly lol
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
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
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
!d discord.Client.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
avoid utils.get unless you don't have any other choice
__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?
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
__init__ is usually reserved for packages
did you do something in the discord dev portal?
ok, actually im talking about making double instances of Events2 class
like?
I didn't do anything
anything OAuth2 related?
no
I've never done that before sorry
oh wait my bad
okay.
whenever I make it so that someone says why in the chat my bot says why not but since it detects why it keeps spamming why not
what do I do
how do I make a bot clear a text channel?
cya
Depending on how many messages are in the channel this may take a very long time. What's the use case?
you could just delete the channel and make a new one with the same metadata
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
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
you don't want your bot to process multiple commands at once?
i think you want a queue or a ratelimiter
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
Exactly, I want one command per user once fetch data is done and embed with info showed to that user
I have tried implementing a cooldown process for each user but does not seem to work as several users can be throwed
It is Blockchain data and when doing the fetch and representing the data in an embed there is no problem or undefined behavior, it works as expected, I’m just facing issues when stressing the bot with several users in a row
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
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:```
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
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
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}")```
Because that's what it is, an AuditLogDiff
the repl of an object isn't automatically what you want it to be
Well, I need it to print the voice channel the member was before he was moved
Is it possible ?
!d discord.AuditLogDiff
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.
Yeah I already seen that but I don't understand how to use it
@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
Remove the indexing [0]
I made *arg
That tells you the attributes that object has
Yes, unexpected behavior when running several commands at the same time, it should only accept one
What is the behavior? What happens?
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
How can I make my bot create an event for this?
Code?
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
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))
Why? What exactly is the user doing, and what is causing issues? Again, we'll need to see code
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
Are you caching the responses from the API at all?
I will be showing the code yeah
Hmmm I dont Solstice
Doing try/except/print is a strict reduction from the default error handling. You shouldn't be excepting ALL exceptions, and only specific exceptions when you have a plan for what you want to do for that exception
Is there a way to get the date of an audit log entry?
other recommendations/steps to fix?
just let the normal error handler print out the full traceback

but you can get an error from trying to dm someone for a number of reasons
!d discord.AuditLogEntry.created_at
Returns the entry’s creation time in UTC.
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?
"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 😭
What library(s) are you using?
Thank you Solstice, I’d definitely say race conditions and mixing, API is not preventing me of pulling data but I don’t want an user to do a fetching loop if introducing several commands in a row
It's worth identifying what you're doing inside of a command
that would be impacted by something out of it
How does AuditLogEntries limit works?
Well didn’t mention but I am scrapping first part of message with startwith function and detecting commands in that way
There's really no reason to do that yourself over just using the built-in command framework, but that wouldn't cause race conditions
Consider implementing slash commands and responding ephemerally rather than dming them
DM's are annoying, invasive, very heavily rate limited and not guaranteed to work
Thank you, problem I see is users need a separate space to do the checks due to privacy so I can’t have a general channel for everyone where they are running the commands
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
ephemeral
Sorry Solstice, don’t understand the term
is there any easy way to get the unicode Ids for emojis in discord?
https://unicode.org/Public/emoji/
https://www.unicode.org/emoji/charts/emoji-list.html
Something like that?
Thank you Crypton
This is kind of a diagram of the APP I am trying
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
What do you think the problem will be
I think there's a bit of a misunderstanding how asyncio works
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 :))
Yea, but people already joined the server so I have to check the past...
Then you don't know
Are you sure that's not possible?
Resources for dpy?
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.
Yes this is not in effect yet, but it will be later on, I am just asking tho.
If you are monetizing your bot anywhere, you need to also monetize it on discord for the same price or less
But my bot is not verified?
How can I monetize it when its not verified?
Thats why I am wondering if those rules only effect apps that are verified.
you can't monetize it if it's not verified
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.
i jus watched NTTS' video on it, explained it pretty well
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"
Its not NTTS job to explain Discords rules.
Do not rely on youtubers to explain your legal obligations to you lol
Literally what I said 😭
was agreeing with you
Yeah and I was agreeing with you too xD
Like this gui like thing
I need this I want to make a yes or no type thing
Embed?
Yeah Is that what they are called?
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...
what do you mean
Like can a user send an embed
nope
only way if a website has an embed like https://youtube.com
Wait since when you can moneytize discord bots ?
For awhile man..
Aren't they allowing Users to send embeds soon..?
Maybe im wrong.. but thats what I remember
havent heard anything
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.
I mean there are user apps now which can send an embed for you I guess
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.
async def my_hook(...):
...
bot = commands.Bot(...)
bot.setup_hook = my_hook
nice, thanks.
and in this case my_hook takes in bot: Bot?
yep
👌
interesting for some reason it seems to skip my own setup_hook and then instantly close my discord bot without doing anything F.
ah I see
F
it seems the replaced setup_hook no work.
There should be some errors, did you call bot.run()/bot.start()
setup_hook gets triggered inside them
I use bot.start ye
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)
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
I cannot because I would like to define it in a C extension and there is absolutely NO way to have a C extension set tp_base to Bot that is defined in discord.py (pure python code) inside of a PyTypeObject * pointer (it would instead default it back to the builtin object type or error out).
how about this solution
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.
😭
You don't need the class
You can assign the method to anything
Or use the event decorator
But also you could just load the extension inside run_bot
Anybody got any ideas on how I can format this better?
heh. figured it out
Do you really need the "Revives:" text
Instead of just
- Name: 112
- Foo: 600
...
Or
- Name
112 - Foo
69
Ended up going with this
Now look at that on mobile lol
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
I do admit not being a master in understanding how asyncio works yeah
Good morning Everyone
Why are they queuing? That's you deciding to do that
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
That's not something that would natively happen in asyncio unless you are choosing and designing it that way
tried adding threads so I could somehow execute the fetches in a concurrent mode since each thread would pull its data but no way
You don't need threads
My question Solstice, sorry if newbie, is it possible executing concurrently each fetch_data ?
You need to understand how asyncio works
That's okay
No deeply understanding but not messing when using them either
does not fix my problem anyways
asyncio is already doing this for you in an async framework like dpy
why in my log I then see they are not running concurrently
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
it is absolutely secuential
can I paste code blocks here?
the core ones to see the exec model?¿
Here or in a paste service if its too long
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
can be screenshots of code?
Not ideal
just use pastebin
You can't put text inputs on message views. Only modals
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]
You have a lock right there
You put that in intentionally
Also lots of unneeded asyncio.create_tasks
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") ```
Yeah.... That's why struggling as I thought tasks would help for the concurrent model but they do not actually
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"
The log does not show that Solstice . . .
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
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
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
would you get rid of the create tasks as well?
I would suggest actively trying this. Do a random sleep then a print, and send a bunch of messages. You'll see that they all come back in concurrently, and that anything that's not concurrent is due to something you're adding
Yes, until you understand the case where you'd need it
You can just await async calls
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
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
it was not my question but okay
I may have explained 10 times already since posting in this channel yesterday
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
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
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
Any doc you’d recommend apart from official ones ?
There's an interactive tutorial somewhere that never got finished but covers the basics
Thank you so much Solstice, I will def take a look
#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
How can I make some bot.tree.commands be shown only to some roles?
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?
Server settings -> integrations -> your bot
Pretty sure I told you that's because that's how the repl for that object works. It doesn't magically know how you want it to print, it's just an object
Then how can I use it?
Like you use any object. Access its attributes and print whatever you'd like in whatever format you want
It's attributes don't have any info it them
And how are you determining that?
Don't trust your IDE, they lie pretty often
Hi
Which option would I need to input?
İs here general chat?
One more question aside from execution, I guess I can’t show a list of available commands when typing ‘/‘ as I am not managing the bots with builtin command function right?
!d discord.AuditLogAction.member_move
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.
You are currently internally listening on your bot for text that looks a certain way. Discord knows nothing about this. If you want the / menu to be populated, you need to publish app (slash) commands to discord
Thank you, but I can't figure out which channel the member was before and which channel he was in after moving
It only shows the before or the after
Is it possible to configure that?
The audit log may not record where they were in. It's telling you how to access which channel they were moved to
Yeah it actually doesn't.
Thank you sm for your support, really helped me out!
Look at your variable called Bot and what you're doing with it
ok thx
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
you could index it but theres prob a better way
this is more suited for #1035199133436354600 , but all datetime objects have a .day attribute
I'm not using datetime though
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
Oh
https://docs.python.org/3/library/datetime.html#datetime.datetime.day
https://docs.python.org/3/library/datetime.html#datetime.datetime.astimezone
alternatively instead of .day, you could use .strftime() which is more convenient if you later need to print multiple attributes from your datetime
https://docs.python.org/3/library/datetime.html#datetime.datetime.strftime
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
I only need the day because I'm trying to only get the logs of the time past 12:00AM this day and I'm using the "day" to play with it
like,
if entry.created_at.day != 24 then: return```
Something like that
Anyways, you solved my issue here so thank you!
audit logs? i thought dpy has a before= and after= parameter to only fetch logs in a certain time range
!d discord.Guild.audit_logs
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}')
```...
Oh wait
BRUHHHHHHHHH
Why did I not think of thatttt
lol
Well anyways it works now so who cares I guess
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
I guess I could and have a cog class inside the main cog file do the ready event with a bool that makes it only ever print once.
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?
what's the maximum amount of buttons one message can have?
5 rows of 5
thanks!
!intents
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.
chat, i was making the ai bot and uh, i got an error
your json is not json
true
try printing the json and see what it says
print the response and see if there's any error
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 😭🙏
that's an html page
...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
are you making a request to the right url
i have stupid question
yep
await ctx.author.edit(nick="idk")
whats wrong with this
it keep not working for some reason
bot i admin btw
error?
bruh 💀
have you set up logging
are you starting your bot with bot.run?
ok, thx :>
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 😫
is the bot role above the role of the member you're trying to edit the nickname of?
well, where do i put the api key
yes!
but idk how that is related
you can't edit the nickname of someone whose top-role is above yours
as the bot is changing the nickname of the username it got nothing to do with the role
im owner
Yeah, then that's the reason
also im changing my nickname through command
?
The bot can't edit your nickname if you're the owner
Yeah, if the bot's top-role is higher than their top-role
is there a way i can bypass this obstacle for the owner
no
😔
At the bottom of the example, in Text2ImageAPI
oki
I'm not familiar with this service so can't really help you further
help guys i need to make myself admin without commands
i got termed and lost my server
contact discord support
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
The pg_dump or pg_dumpall shell commands
Oh shit ur right
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?
You may wish to do a little debugging and see what your call to audit_logs is returning
Hey, I did actually, but anything after the last line of the "member_move" entry log is just not working
Any idea why entry.target.is_timed_out() prints out this error: 'User' object has no attribute 'is_timed_out'?
Because User objects aren't tied to a guild and can't be timed out
Ohh
By the way, entry.user.id prints as NoneType
But only when I check the member_role_update
It works fine for anything else
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?
I would recommend not doing these in the same process anyways
!d discord.ext.commands.Context.reply
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`.
thxx
how can i make a ctx.reply, not mention the member?
👍 if you want to lookup other docs, try in #bot-commands
as for that, you'd pass mention_author=False
thank you mate
How can I make some bot.tree.commands be shown only to some roles?
using @bot.tree.command()
for app commands it has to be done in the server's integrations tab, bots cannot set specific roles/members/channel overrides by themselves
oh
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
so I have to make it by hand? cant I make it somehow like py @commands.has.any_roles[ROLE'S IDS HERE]
there is a non-native check built into discord.py for that
!d discord.app_commands.checks.has_any_role
@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.
but it won't be able to hide your slash commands from users unlike the native permissions
@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...
?
for permissions you can set native default permissions
!d discord.app_commands.default_permissions
@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.
hm okayy, thx for your help 
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
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
You have to respond within 3 seconds
defer then followup
any reason to this? ive had this problem before and never got a fix
Code?
!paste
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.
You can't followup before responding
^^^^^^^^^^
AttributeError: 'str' object has no attribute 'author'```
why can't i do this anymore 😭
Read the error
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?
what's the error?/ do you have an error handler?
what is ctx
show relevant code
You also have no logging, no way to tell what's "being ignored" as most of your code would just silently run anyways
No error
I had logging, but it didn't help so I removed it
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
It's not working because of how the loop works probably, because I tried switching the positions of the loops in the code and it seems that the only one messing up the code is this

Do a defer() of the interaction
In case it takes more than 3s to respond, Discord will wait for it to finish
Any other error besides that one?
how do I reduce my bot's load? Like i don't wanna cache any guild where the bot is not used
Wdym not used
you can turn off guild chunking at startup and chunk guilds when you need it
That may affect the performance of the bot, usually not recommended, responses may take longer but you can turn off guild chunking as Willi said
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
Yeah but after an event/command is used i don't think it will take excess time to respond again?
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
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.
Is it possible for a discord bot to manage the guilds integrations?
Specifically the section that controls the commands
Adding bots is not what I want. I want to be able to make a command visible to only specific people and roles
oh
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..
perhaps @app_commands.default_permissions()?
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?
sure
Reload discord
Ctrl r
nope still nothing. im pretty sure its something to do with the code?
Are you syncing your commands to the server?
So how am I gonna be "Already subscribed" to it. But not be subscribed to it?
How do I even fix this issue...?
:/
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.
yeah
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)
Whatever feedparser is, it's blocking. Also don't use on_ready for things you want to happen once
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}
")
await channel.send(embed=embed)
else:
print("Channel not found")
else:
print("No boost change detected")

There is not a reliable way of detecting this. That bot is making guesses
you could check for the message discord sends when someone boosts
that specific message type
(Which relies on a) the guild enabling that and b) the bot having read permissions where it's sent)
yeah
what about checking for the nitro booster role?
you could check for that role with on_member_update
I tried that too but it didn't work
I'm a noob so it's probably on me xd
That does not fire for subsequent boosts
ah ok
Ohh I'll check it out
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
Hmm Idk how it does it 
It's not doing it reliably. It is guessing