#discord-bots
1 messages Β· Page 1 of 1 (latest)
display_avatar
no need to be sorry lol
interactions use webhooks so maybe that?
The interaction token is invalidated so yea
Maybe your bot is taking too much time to respond to the interaction... Maybe
Try deferring it
No idea for nextcord. I've only used dpy
i need to check if bot top role > member top role.
how?
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
I tried this:
if self.client.top_role.position < member.top_role.position:
but not working
Defer it in start and do whatever you want to process in your command and respond with a followup
hi
client, a discord.Client/Bot instance do not have any top_role. It's the discord.Member
there must be something like interaction.followup
when i use command with this check the whole command fails
without - ok
and how to check bot top role?
hm..
Get the guild bound instance of your bot, i.e., a discord.Member instance and use top_role on it
!d discord.Guild.me better
property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
I'm getting this error now:
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token
!d discord.Role.position actually there is a warning for that here
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
Why everyone's getting the same error π
becuase i dont know how to pycord lmfao
Uhh so you responded normally to an interaction but now needs to respond again.. right?
There's a followup webhook you can use
But iirc you need to defer your response or something like that to use it otherwise it's interaction token will be invalidated
There's some complex shit going on with followup webhooks. https://gist.github.com/AkshuAgarwal/bc7d45bcecd5d29de4d6d7904e8b8bd8#interactionfollowup I wrote this about an year ago so I don't know how much of it is still valid but it has some basic info how it works.. If you anyway wanna check it out, sure.
why does my bounty command not work. the rounded value IS printed but no embed is sent
@client.command()
@commands.cooldown(1,10,commands.BucketType.user)
async def bounty(ctx):
worth = random.randint(1000,100000)
rounded = str(round(worth,-3))
print(rounded)
if bounty <= 10000:
mbed1 = discord.Embed(
title="noob monke. imagine low bounty",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed1)
elif bounty >= 10000:
mbed2 = discord.Embed(
title="u are good but not enough to be pro monke",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed2)
elif bounty >= 50000:
mbed3 = discord.Embed(
title="pro monke, must've done some bad things to get this bounty",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed3)
elif bounty >= 75000:
mbed4 = discord.Embed(
title="damn, certified pro monke. I wonder what you did to have such a bounty",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed4)
elif bounty == 100000:
mbed5 = discord.Embed(
title="OUR LORD AND SAVIOR. WE SHALL MAKE A CREW AFTER YOU: MONKE PIRATES. WE SHALL PROTECC DA CAPTAIN!!!",
description=f"{ctx.author} is worth {rounded} monkeybux!"
)
await ctx.send(embed=mbed5)
because bounty -> function
Also your if elif statements doesn't seem correct. A value of 75000 will be responded 3 times with the embed of 10000
made a boolean which stops that from happening
didn't understand
!e ```py
bounty = 75000
if bounty <= 10000:
print(1)
elif bounty >= 10000:
print(2)
elif bounty >= 50000:
print(3)
elif bounty >= 75000:
print(4)
elif bounty == 100000:
print(5)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
Got it?
Read your code carefully and see what's bounty. You probably wanted to use rounded
oh im blind*
Do it this way instead ```py
if 0 <= bounty <= 10000: ...
elif 10000 < bounty <= 50000: ...
or
if bounty in range(0, 10000): ...
elif bounty in range(10000, 50000): ...
No you're not. You just didn't pay attention
It's a discord glitch, just as side note
Just gotta wait for discord to fix it or revert the changes

Hi everyone. There is currently an issue being investigated with interaction edits, deletes, and followups. This issue results in receiving
50027: Invalid Webhook Tokenerrors when trying to edit, delete, follow up, or take some other actions on interaction webhooks.
how to get command message and delete it?
if its a prefix command, you can get it using ctx.message
!d discord.ext.commands.Context.message ?
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is βsyntheticβ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
why does this not work? https://hst.sh/omogijebiy.py
bot loads up fine and stuff but the commands arent coming and jishaku also isnt recognized
setup_hook outside the class
it doesnt work even if i put it in the class
so if i do this it still wont work
await bot??.load_extension
what
Uh maybe it's correct but you can just use self.load_extension I guess
Also iirc it's non-asynchronous method
yeah it is but like when i restarted my bot after like a year it kept screaming at me that its not
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
PS C:\Users\Administrator\Desktop\Flly Bot> & C:/Users/Administrator/AppData/Loc
al/Programs/Python/Python39/python.exe "c:/Users/Administrator/Desktop/Flly Bot/
main.py"
Traceback (most recent call last):
File "c:\Users\Administrator\Desktop\Flly Bot\main.py", line 249, in <module>
bot.run(TOKEN)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 715, in run
return future.result()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 694, in runner
await self.start(*args, **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 599, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000084A8B29430>
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
PS C:\Users\Administrator\Desktop\Flly Bot>
what is that?
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('xxx')```
is it ok ?
error in 3rd line
π€
Have you tried reading the error?
oh sorry i missed thattt
still nope
have no idea whats wrong
error?
i'll also suggest to name folders with characters like -, use an underscore instead ( tho its irrevalent here)
its just Command "jsk" is not found
are you using discord.py 2.0?
why else would the name their cog folder slash cog π
cause yes

π
IVE BEEN DEBUGGINF THIS FOR 3 HOURS
thats why you don't keep multiple versions of python
BRO IM IN A VENV
WAIT NO I DIDNT DO THE SOURCE COMMAND
u have Ultron in ur system then
hhaahaha programming is my favourite past time hobby Hahahah
Lmao π
π
.
Do assert discord.__version__.startswith('2'), "run the source command dude"
Always helped me to remember to turn on venv π
yoo at least i know that my cog got loaded
imagine your linter not shouting
π not test the jsk command
I code in notepad
vim when
i cant i gotta debug the cog first or else the bot wont run
π
also anyone know how to tell me which line number the error is in the actual file of the cog
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This must be called for the application commands to show up.
2-3 line
like this?
the setup functions now need to be coroutine
it's in file_name:line_num format
!d discord.ext.commands.Bot.add_cog is async too
await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a βcogβ to the bot.
A cog is a class that has its own event listeners and commands.
If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the botβs [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.
Note
Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")βs [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
start working binary directly no need to even learn programming languages
i wish this will make people stop importing the cogs and adding them in their main file
use brackets
Cant use special nos in binary π
me who has a cogs.py that imports literally every cog
π
how to get member for unban?
hi
me who doesnt use cogs
wdym
!d discord.Object use their id
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create βminiatureβ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the objectβs hash.
async iterator for guild.bans
no ew
i'd rather perform an invalid unban operation than fetching the ban list and checking if the user is actually banned or not
y?
same amount of requests, less pain
what ever suits u Β―\_(γ)_/Β―
this is where you mention lightbulb's plugin system
yes
not really
sus
i dont use lightbulb anylonger, made my own command hander 
nah
import hikari
import dawn
ext = dawn.Extension("extension")
@ext.listen_for(hikari.MessageCreateEvent)
async def event_example(
event: hikari.MessageCreateEvent,
) -> None: # NOTE: this does not support annotated event
print("Message created.") # mention the event class in the decorator.
@ext.register
@dawn.slash_command()
async def ping(ctx: dawn.SlashContext) -> None:
await ctx.create_response("pong!")
def load(bot: dawn.Bot) -> None:
ext.create_setup(bot)
``` totally not inspired from lightbulb
is it named after pydis' mod dawn?
hikari - light
dawn - time at which first light appears in sky
cool
while True:
time.sleep(0.2)
random.choice(userr)
embed.add_field(name="Avaliable User β
",value=random.choice(userr),inline=True)
await ctx.reply(embed=embed)``` can anyone fix this issue, it adds on more random.choices to the embeded
it adds on more random.choices to the embeded, elaborate?
you want it to be same for all the replies?
!e ```py
import random
a = [1,3,4,5]
for _ in range(2):
print(random.choice(a))
!e ```py
import random
a = [1,3,4,5]
var = random.choice(a)
for _ in range(2):
print(var)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1
002 | 1
Okay thankyou!
Hikari looks like the kid who does everything, but the harder way π
doubtπ
new kid = cool
they just didnt implement any fancy abstractions, everything's native and accords to the raw discord API
yeah?
kiba gonna be sed π
you dont wanna see how slash commands work in hikari without a command handler
That's my most beginners (in python) does not prefer hikari
i mean thats good isnt it, let dpy bare all that headache
Exact same issue.
show updated code
Yeah true
Says await outside of function
@bot.command() async def user(ctx): embed=discord.Embed() a = ["sicud","qiied","iwudj","7w8xi"] var = random.choice(a) for _ in range(2): embed.add_field(name="Avaliable User β
",value=random.choice(a),inline=True) await ctx.reply(embed=embed)
did you save and rerun?
You don't just copy and paste the stuff..? Try to understand what they meant
Yes
You're still doing same value=random.choice
and you are still not using the variable i declared for the value kwarg
and for loop is outside the function
how to unban by id?
await Guild.unban(discord.Object(id=id))
bot = commands.Bot(...)
@bot.command()
#add permissions
async def unban(ctx: commands.Context, user_id: int) -> None:
await ctx.guild.unban(discord.Object(user_id))

thxβ€οΈ
How bad is the idea of having cogs as separate repos in a GitHub org and link them back to the main bot with submodules tracking the master branch of the cogs
a really bad idea, dont know why you would want that
"Because I want it" is one
!d discord.Object id is a kwarg nvm me
πΆββοΈ or not wtf
And why is it bad?
waste of resources
in the first place, plus no control over different files by the main file
Can you elaborate?
The first part I can understand: Lotsa .git means more space consumed. But not quite the second
how are you planning to load that cogs then
clone the repo, copy the path and load it?
how is some bot seeing git commits
you mean the bot named "GitHub"?
yeah
git clone --recursive, and since I'm using hikari-lightbulb, bot.load_extensions(). From the bot's perspective, it's just a normal day....with a few .git directories
not like its not possible, but thats totally overkill
ok thanks 
The traditional monolithic approach is fine. But this mainly comes from the expectation of me writing some hefty extensions that might need a separate repo for tracking. And since the design doc is pretty much WIP, I don't mind changing a thing or three
why a seperate repo, just create another branch....
Ah screw it. It's possible, yes?
yeah~
if you still persist on using another repo, you could've used bot.load_extensions_from() as well because it loads all the extensions in the directory ( except the ones with _ in the start )
how to check user in ban or no?
well you cant do that unless you search the audit log
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
Changed in version 2.0: Due to a breaking change in Discordβs API, this now returns a paginated iterator instead of a list.
Examples
Usage...
Why don't I get errors in cogs?
thx
Wym
Let's say I have an error in embed, I didn't write description, but somehow differently. In this case, I don't have an error.
Idk maybe u have the try keyword
description is optional to have in an embed
you can even have embeds without titles 
Q; not at home at mo and on my phone. Am I correct in thinking I need to create an app on reddit in order to get like random images, posts, etc from what ever subreddit I add in my code? A few people seem to say you do where others dont.
Yes and no, not necessarily
just use an api 
You can just make a request to https://reddit.com/r/<subreddit>.json
or that
If you use a library like Praw (I think it's that) it will require you to bave an app on Reddit, kind of overkill depending on what you want
Discord: "everyone, move to slash commands"
Also Discord when they break: "imma just quietly wait for people to start their day"
fr
They haven't called any engineers to fix the issue
Ok cheers much appreciated, worked with apis in terraform/ansible so should be OK, I'll look at the json one too see which one I can get working... Thank you!
They're just waiting for them to come and start their day 
No problemo 
I don't believe you do, but the ratelimits are kind of harsh for those without an app
ah well
Discord's issue is related to the snowflakes getting a new digit
Kind of expected at this point and even predicted it yesterday
Discord after all
They had 7 years to prepare for that..
Any idea why setup_hook doesn't get called?
Could we see the code?
I subclassed discord.ext.commands.AutoShardedBot (discord.py version 1.7.3)
What code do you need to see?
It's an asynchronous method I've overridden in my subclass
I have also overridden run:
def run(self) -> None:
print("Ran run()")
super().run(os.getenv("DISCORD_BOT_SECRET"), reconnect=True)
The print works and the bot runs
It just doesn't respond to messages because I've made it so it returns in on_message if a database connection was not made
setup_hook is supposed to setup a database connection
But setup_hook simply doesn't get called
At least so it seems
There's the problem
setup_hook is a feature of v2.0.0^
hey I have a pretty simple question, but I can't seem to figure interactions (specifically buttons) out with discord.py, could someone tell me how they work?
is there any way for my bot to delete all messages with the selected word
like.. delete past messages also
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\channel.py)
anyone know how to fix this?
Recently I uninstalled and installed discord.py module, and after I reinstalled it, this error has been coming up every time I run a discord bot
https://github.com/Rapptz/discord.py/blob/master/examples/views/tic_tac_toe.py this is a pretty advanced example, but covers most usecases of buttons.
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py more basic example that covers how to make a basic view with some buttons that have functionality
thanks so much!
Is there any easy method of doing pagination?
Like an external module that could work with disnake? or like an example code
!pypi discord-ext-menus
An extension module to make reaction based menus with discord.py
Or make your own paginator plugin
Oo ill have a look at that
Sure. Also if you need buttons instead of reactions, I have an old implementation of the same you can use that https://github.com/AkshuAgarwal/Aperture/blob/51239bf4e5f942c1e9ed4c67e982f45496f84ae2/aperture/utils/paginator.py nvm it wont work with disnake anyways, I didnt read that
how do we help if u don't tell what the exercise is
how can i deselect the selected value in menus using discord.py?
I think #python-discussion would be a better channel for this (or anything not related to discord bots)
i must use python to make features about txt files
i want to read txt files with python
and make some calculations
about duration
For example i have a menu they can select the type of ticket channel they want to open, and i want it that after the selection is made, it clears the selection so they can create an other ticket channel from that type
u can reassign a new view?
or rather the old view
i cant just clear their selection?
???
Halo
Hello*
How j can make a cmd that ads bot to a voice and never leaves voice till his online?
anyone can help with this?
what command did u use to install discord.py?
pip install discord.py==0.16.12
There u go
The latest version is 2.0 (still in dev tho)
0.16.12 is HELLA outdated
ohhh, I'll try to update it rq
just do pip install -U discord.py
I still get the same error
pip install -U git+https://github.com/Rapptz/discord.py.git
@bot.command()
async def ping(ctx):
await ctx.send("Pong!")
replica site?
Eh, replit isn't preferred
can you recommend a coding program?
worked, thanks mate
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
The docs have a short tutorial
To code, you can use it, it's actually an online repl. But if you're planning to host it on that site, please no.
Best would be to use a local IDE (I personally prefer vscode)
he has done projects in vscode but how do I start the bot from it?
You write a program in it and run it using a terminal, like you do run other python files...?
Or do you mean something else
I know how to save the project, but the point is that I don't know how to start the bot to be online
You just need to run the file...
yes
Wait do you mean how to write a script to create and connect the bot?
Uhh nvm, what have you done/created so far?
no, I want the bot to start, to be created and invited to the server, I know
and excuse the accent, but I'm from Romania
Np that's fine
^^ ?
async def on_guild_role_update(self, before: nextcord.Role, after: nextcord.Role):
was_updated = (
before.name != after.name
or before.colour != after.colour
or before.permissions != after.permissions
or before.position != after.position)
if was_updated:
embed=nextcord.Embed(color=0xfd9fa1, description= f'{after.mention}\nColor: {after.colour.value}\nName: {after.name}\nPermissions: {after.permissions.value}\nPosition: {after.position}', title='Role Updated')
how can i edit this so that it shows a hex value for color, and so that it tells what specific permission was changed?
!d hex
hex(x)```
Convert an integer number to a lowercase hexadecimal string prefixed with β0xβ. If *x* is not a Python [`int`](https://docs.python.org/3/library/functions.html#int "int") object, it has to define an `__index__()` method that returns an integer. Some examples:
```py
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
``` If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways...
Is it possible to send a modal from the interaction you get from the submit of another modal
so sending a modal from a modal
Said again, out of my expertise
Guys, can someone help me add a image to my command
Yeah but why lol
A few questions:
Where are you hosting this bot, locally, or somewhere else? (State where if somewhere else)
Have you got any code for your bot?
Have you created a bot, generated a token, given it any permissions and intents in the discord dev portal?
Have you got any fundamental knowledge in python?
Answers to these will be able to let others assist you π
is there a way to configure on_role_update's before.permissions and after.permissions so that you can see which permission got turned on or off? im not sure how to code it
W i use nextcord too
yeahh i switched after my friend told me nextcord is better since discord.py isnt supported
For some reason the typehints in discord.py are a little weird...
Like, the rpc_origins in AppInfo is typed as List[str] and in PartialAppInfo as List[str] (yeah both are same)
Whereas, the privacy_policy_url in AppInfo is typed as NotRequired[str] and in PartialAppInfo as str (Makes more sense I guess)
According to discord's docs, they both share the same structure, rpc_origins? and privacy_policy_url?, means they might or might not exist in the payload, doesn't really matter... But they're typed differently in dpy. So what's the deal with these typehints?
guys i need help when i type a command or sth and i expect my discord bot to act with some message for exemple : "hello" the bot sends "hello" twice,its obvis hosted from 2 different servers , the site iam using to host my bot is "railway" but idk the other one iam so confused, is there a way to find it using the bot?
smh sould i just regenrate the bot code?
Probably an orphaned instance somewhere. Regen the token, should fix it
yep it worked
Idk how to use the new modals yet
I wrote an example for it: https://github.com/Rapptz/discord.py/blob/master/examples/modal.py
@commands.command()
@commands.has_permissions(ban_members = True)
async def unban(self, ctx, user_id: int = None):
log = Logs(ctx)
db = Guild()
author = ctx.message.author
guild = ctx.guild
banned = await guild.bans()
if user_id is None:
await ctx.message.delete()
print('1')
embed = discord.Embed(description = f"{author.mention}, ΠΠΈ Π½Π΅ Π²ΠΊΠ°Π·Π°Π»ΠΈ ΡΡΠ°ΡΠ½ΠΈΠΊΠ° Π΄Π»Ρ ΡΠΎΠ·Π±Π°Π½Ρ.")
embed.add_field(name = "**ΠΡΠΈΠΊΠ»Π°Π΄:**", value = f'**{db.get_bd_prefix(ctx.guild.id)}unban** `id Π»ΡΠ΄ΠΈΠ½ΠΈ`.')
await ctx.send(embed = embed, delete_after = 10)
return
for user_ban in banned:
ban_memb = user_ban.user.id
print(ban_memb)
if ban_memb is None:
await ctx.message.delete()
embed = discord.Embed(description = f"{author.mention}, ΡΡΠ°ΡΠ½ΠΈΠΊ `{user_id}` Π½Π΅ Π² Π±Π°Π½Ρ")
await ctx.send(embed = embed, delete_after = 10)
return
if user_id is ban_memb:
emb = discord.Embed(description=f"**ΠΠΈ Π±ΡΠ»ΠΈ ΡΠΎΠ·Π±Π°Π½Π΅Π½Ρ Π½Π° ΡΠ΅ΡΠ²Π΅ΡΡ {guild.name}**", color = 0x6d41a8, timestamp=ctx.message.created_at)
emb.add_field(name="**ΠΠ΄ΠΌΡΠ½ΡΡΡΡΠ°ΡΠΎΡ:**" ,value=f'{author.mention} ({author})', inline=False)
emb.set_footer(text=f"By {guild.name}")
await user_id.send(embed=emb)
embeds = discord.Embed(description=f"{user_id.mention} **Π±ΡΠ² ΡΡΠΏΡΡΠ½ΠΎ ΡΠΎΠ·Π±Π°Π½Π΅Π½ΠΈΠΉ!**", color = 0x6d41a8, timestamp=ctx.message.created_at)
embeds.set_footer(text=f'By {author}')
await ctx.send(embed=embeds)
await ctx.guild.unban(ban_memb)
await ctx.message.add_reaction('π')```
where error? i checked this code but didnt find an err
If there was no error here, it should be good then, shouldn't it?
Unless of course you've got a faulty error handler
i know, there is an error here. but... where? I watched for a long time, checked, rewrote ... and nothing..
You canβt hide it but you can make it grayed out
!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 "discord.app_commands.check"). Therefore, error handlers are not called.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
So can we see the error?
Well it's hard to diagnose and fix an issue with knowing what's wrong
If you can't send us the error, we unfortunately cannot do much to help
i dont have error in cmd. just everything in the for loop does not work
That means banned is probably empty
Also, am unban command does not have to be this long
it should be like 4 or 5 lines if we're talking error handling
I have a problem on my bot #help-potato
does youtube_dl still exist? i cant find the module
when i do Import youtube_dl, it doesnt work
i have it downloaded
Anyone got ideas how i can fix this? https://femboi.best/zDuNiDn6
I need to show the image in the embed, its stored locally
Idk any other way rlly
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)
Note that the filename in the File constructor and the filename in the URL must match, and must be alphanumeric.
Ohhhhhhhh, tyty
π
Guys how I can i make a leaderboard comamnd using a sqlite database?
leaderboard command of what? coins?
My friend have made a bot and he have a game so he need a leaderboard for it
but you're not your friend, why are you asking
E.set_image(url="attachment://image.png")
Is this linking to a directory? As it ran without error but the image didnt show in the embed
ok whatever, SELECT * FROM users ORDER BY coins ASC
obviously replace table/column names with yours
url="attachment://<whatever_filename_you_set_in_f>"
I mean how I can get top 10 users
f being the discord.File object
Oh, yeah hm. Didnt work but there is a error
add the LIMIT 10 clause
Oh k
Uh the error seems self explanatory but Iβm not sure why itβs happening
Yeah, weird..
it does delete the file after yes but still, it deletes after the msg is sent. Thats super weird
Huh
Try saving just one discord.File object and using it everywhere
Or maybe this
Wut
I thought that existed
does youtube_dl still exist? i cant find the module
when i do Import youtube_dl, it doesnt work
i have it downloaded
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
how do i get it to display an error msg in the console? it says nothing'
Code
I migrated from Replit to Google Cloud to run away from rate limits, and now I'm even more rate limited and can't understand why at all
I donβt necessarily think this is an error
More so blocking code or something taking a long time
i fixed it dw
it was the dumebst thing ever, i was doing interaction.send instead of send_message
π glad you fixed it though
how can i make a log that shows who disconnect a user from a voice channel?
how can bots edit their message?
store the sent message in a variable, then edit it using .edit (if dpy)
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
thanks
? help
Do I need to enable intents even if my bot is verified?
Oh...i see
It's actually why intents have been added
Plus you need to give a valid use case for every intent you want to be enabled when doing verification. And after your verification you need to create a new support ticket explaining why you need it.
how to send ephemeral message just using discord.py?
its only for interaction
you can only send ephemeral messages when you have an interaction such as button click responses, drop down responses, slash command responses
And you require discord.py 2.0 or above to use interactions
oh okay thanks a lot!
Guys why this error is coming
I dont even ahve a slash command but it's showing a slash command
there's some issue with your command tree
But i don't have comamnd tree
code?
Ok
async def on_message(msg):
if msg.content.startswith('+email'):
<sends message saying hello!>```
Sus error
Don't use the event to make commands, use the commands extension
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
async def email(ctx):
time.sleep(1)
await msg.add_reaction(':white_check_mark:')
await msg.delete()```
like this?
Don't use time.sleep it will block your code
what should i use to add delay
await asyncio.sleep
await asyncio.sleep(1)
like that?
Though it will wait 1 second, add the reaction and instantly delete the message
So you probably want to put it in-between
await ctx.send(arg)
after doing this:
i want it to delete it after 1 second
await ctx.send("Message", delete_after=5)
oh wow
kk thank you
Will delete after 5 seconds
this solved like 80% of my problems
await ctx.send("Email Sent", delete_after=5)```
if i do this will it send the first message wait for 5 seconds then send or will it send both messages and after 5 seconds it deletes both
both
kk thank you
It will send them one after the other
And each message will wait 5 seconds independently and then get deleted
exactly what i wanted
oh, i thought you needed to add an interval for that to happen.
They will be sent one after the other
how do i store the next users message as a variable
Instantly
Pls help
But the time they get removed is not related to the other message
It won't "delete both"
It will delete one after the other, maybe with some milliseconds interval
lol
The command is not found...?
I dont even have slash command
how do i get the next users message
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
And wait for a message
Wdym
Pretty sure there is an example if you click on it
like the next message the user sends the bot gets it and stores it as a variable
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,help_command=None,intents=discord.Intents.all())
async def setup_hook(self):
print("Loading cogs . . .")
cogs = []
try:
for f in os.listdir("./cogs"):
if f.endswith(".py"):
cogs.append("cogs." + f[:-3])
for cog in cogs:
await bot.load_extension(cog)
print(f"{cog} was loaded")
except Exception as e:
print(e)
self.connection = await aiosqlite.connect("prefixes.db")
print("connected")
self.cursor = await self.connection.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.cursor.execute('CREATE TABLE IF NOT EXISTS afktable(user_id INTEGER ,reason TEXT,time BIGINT)')
await self.connection.commit()
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connection.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connection.commit()
return prefix or '>'
bot = botclass()
async def email(ctx):
await ctx.send(arg)
await msg.add_reaction('β
')
await asyncio.sleep(0.5)
await msg.delete()
await ctx.send("Sending Email", delete_after=60)
await ctx.send("Code:", delete_after=60)
asyncio.wait_for(x)
await ctx.send(x)```
would this work?
AHH MY BRAIN CANT UNDERSTAND IT
And if you want "Sending Email" and "Code:" to have a 60 seconds interval, use await asyncio.sleep(60) between both
oh no
i want both of them to send at the same time
then both of them get deleted after 60 seconds
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
msg = await bot.wait_for("message", check=check)
await ctx.send(f"Hello {msg.author}")
That is basically the example
im. going to get this and chainge a bunch of stuff untill i understand
async def email(ctx):
await msg.add_reaction('β
')
await asyncio.sleep(0.5)
await msg.delete()
await ctx.send("Sending Email", delete_after=60)
await ctx.send("Code:", delete_after=60)```
when i try running this it keps saying msg isnt defined
oh wait i know
msg = ' '
nvm i dont know
i want it to delete the message that the user sent
use ctx.author
to get that message you use ctx.message
await ctx.message.delete()
like that?
yuh
iscord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Message.delete() takes 1 positional argument but 2 were given
https://media.discordapp.net/attachments/343944376055103488/1000319743158403103/Screenshot_2022-07-23-14-01-51-16.jpg
Guys why this error is coming
I dont even ahve a slash command but it's showing a slash command
Pls help me
perhaps app_commands.CommandTree is the problem
pretty sure it's used for slash commands and ctx menus
I don't have any slash comamnd
Then there's no way the error appears
Cz the error says u got the problem with app cmd
Bro i don't have any slash command
anyone knows the reason to this:
AttributeError: 'Events' object has no attribute 'role_message_id'
trying to use this
https://github.com/DisnakeDev/disnake/blob/master/examples/reaction_roles.py
I just changed the name of the partial emoji
U got any other cog file?
me? well a few...
No, I mean navi
Goodness gracious
it's one per each module 
it's a bot used on a mod server, so basically
one mod -> one cog
What you mean?
You are creating cogs with this, right?
I mean, your other .py file
That's for loading cogs and my database
you probably put something inside the bracket of Message.delete()
it keeps saying channel isnt defined
ima just delete channel
there now it works there is only 1 channel so its fine
oh wait how do i get the input tho it waited for the user to send.. but i need to get the message that he sent
oh
@bot.event async def on_message(message): await asyncio.sleep(3) await message.delete()
you can replace any number with 3 that i have there, that is the interval for which the bot will wait until it can delete the message.
on_message will allow the bot to detect and receive any message
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
@bot.event
async def on_message(message):
if message = 'hi'
like that.?
um
the last 3 lines are looking a little bit funky... you can't leave the last line with a if statement with no followup
ill fix it
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
@bot.event
async def on_message(message):
if message == 'hi':
await ctx.send("hello", delete_after=5)
else:
await ctx.send("not hi", delete_after=5)```
AHH
I HAVE GOTTENMY SELF INA STICKY SITUATION its smamming it
do i use break?
you can use this
@bot.event async def on_message(message): if message.content=='hi': await message.delete()
use asyncio.sleep() to set intervals
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
^ for reference
kk thank you very much
no problem π
how to check if a user is banned?
what?
def random(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
emailnum = random(4)
numb = emailnum
@bot.command()
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
await ctx.send(numb, delete_after=60)
@bot.event
async def on_message(message):
if message == numb:
await ctx.send("Correct Number", delete_after=3)
else:
await ctx.send("Wrong", delete_after=5)
await ctx.send("Please Do The Command Again To Send Another Email", delete_after=5)```
when i make the bot print out message
it does not print out the message it sends like.. idk how to explain it but it isnt the message
Depends
If it's text channel, nextcord.TextChannel
But if it's voice channel, nextcord.VoiceChannel
This is the example for slash commands
async def test(interaction: Interaction, channel: GuildChannel = SlashOption(channel_types = [ChannelType.text], description = "Select text channel")):β
async def check(self, ctx, member): await client.get_user(member.id)
somewhere in that region
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
await ctx.send(numb, delete_after=60)
@bot.listen()
async def on_message(msg):
if any(word in msg.content for word in numb):
print('worked')
else:
print('didnt work')```
if any(word in msg.content for word in numb):
TypeError: 'int' object is not iterable
what the heck does int object is not ilterable
numb has to be in a string
pardon?
str()?
what are you trying to do?
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
emailnum = random(4)
numb = emailnum```
i need to make this
though...
into a string
it doesn't need to be a string if youve already have a value assigned to it
i've bolded it for you.
oh sorry i didn't understood your question at first
im going to have a brain fart
ohh wait i print numb not message
let me print message
oh my god
you can't use ctx under @bot.event because message is already used as an argument for on_message
i defenetly found the problem
oh
ok i found the problem tho
when i print message aka the message that i sent
it gives me this
if message == numb:
that wont work anymore
@bot.event async def on_message(message): if message.content==numb: print('correct number') await asyncio.sleep(1) await message.delete() else: print('Wrong Number') await asyncio.sleep(1) await message.delete()
oh
alright im going to chainge it up a bit to this:
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
await ctx.send(numb, delete_after=60)
@bot.event
async def on_message(message):
if message.content==numb:
await ctx.send("Correct", delete_after=60)
await message.delete()
else:
await ctx.send("Wrong", delete_after=60)
await message.delete()```
and ill sc the problem
that's not going to work
it.. isnt?
!d discord.ext.commands.Bot.wait_for instead of having the event inside the function, use this
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
mann i tried that a bunch of times looked it up a bunch of times
and i have no idea how to make it work
i red it like 5 times i dont understand
its just
message = await bot.wait_for(...)
what should i put in ()
event name
what is a event name
on_message in this case
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
await ctx.send(numb, delete_after=60)
message = await bot.wait_for(on_message)
if message==numb:
await ctx.send("Correct", delete_after=60)
await message.delete()
else:
await ctx.send("Wrong", delete_after=60)
await message.delete()```
wait it isnt defined
https://discordpy.readthedocs.io/en/stable/api.html?highlight=guild#discord.Guild.fetch_ban Looks like guilds have a fetch_ban method
You can just throw the user id in there
If a NotFound error isn't raised then they are banned
is it possible to fetch a guild
And send a message in that guild
yes it is possible but the limitations are that the bot should be in the guild and the channel is to be sent in a channel
message is to be sent*
i'm trying to do it through try except, but my command is in cogs, and there, for some reason, i don't get any tracebacks
Are you trying to print the error?
?
What traceback are you referring to here? If you're suppressing the error what traceback do you expect?
even if I don't suppress the error I don't have a traceback
idk why but in cogs as always
I have
@bot.command()
async def email(ctx: commands.Context) -> None:
await ctx.send("send code")
def check(msg: discord.Message) -> bool:
return msg.author == ctx.author and msg.channel == ctx.channel
msg: discord.Message = await bot.wait_for("message", check=check)
is a simple example of using a wait_for
indenting on phone feels like hell :AScry:
thank you ill use it later
as anyone being able to use
on_raw_reaction_add with disnake? 
@bot.event async def on_command_error(ctx, MissingRoles): if isinstance(error, MissingRoles): error=discord.Embed() error=discord.Embed(title=f" π€ ERROR π« ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00) await ctx.reply(embed=error)
Idk how to fix this issue btw
https://media.discordapp.net/attachments/343944376055103488/1000319743158403103/Screenshot_2022-07-23-14-01-51-16.jpg
Guys why this error is coming
I dont even ahve a slash command but it's showing a slash command
Pls help me
how to edit an embed message into another embed message?
i tried using await sent_message.edit(content=embed2)
but it didnt worked
it adds some stuff like this to top of message but its not changing the embed at all
with open("./guild/guildID.json", "r") as raw:
data = json.load(raw)
with open("./guild/{}.json".format(guild.id), "w") as raw:
raw.write(data)```
`write() argument must be str, not dict` I just want to copy the guildID.json into the new file, can someone help out?
@commands.Cog.listener()
async def on_guild_join(self, guild):
it's btw a listener
@client.command()
async def unban(ctx, *, member = None):
try:
await guild.fetch_ban(member)
print("1")
except Exception as e:
print(e)```
`'str' object has no attribute 'id'`
Just do this @slate swan
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
@commands.has_role("enter role")
go to applications
wait brb sorry
applications > application > general > click on avatar
@slate swan should just be like this
@command.has_role("mod")
so when executed if the user has that role it will run.
Just use role name way easier.
pick your bot
has to be splet exactly
then boom insta edit thing
member: discord.Member=None
wait.. what exactly where you asking when u said how did u make your bot like that
Anyone help me pls!
then I will have an error MemberNotFound
@robust fulcrum show code.
Which part?
names change, ids dont
OHHHHHHHHHHHHHHHHHHHhh
certainly but i just like to use roles its a option lol
discord not bot im sorry
download better discord
if i put it in str(data), it will form it by ' but's invalid and want to use "
oop yes just do
fetch_ban(discord.Object(member))
supposing that member is an id and typehint member to int
@robust fulcrum I recommend downloading pydroid on your android device best py emulater out there avaliable for android and ios !
if you dont want the json to be parsed then open the file using open and read it using .read
with open(...) as f): s = f.read()
here s is a string
ah the bracket after s
Hmm how
ok, and i wanna to send message for member
how?
'Object' object has no attribute 'send'
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'lower'
Ignoring exception in command email:
Traceback (most recent call last):
File "C:\Users\Tim Oliver\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Tims_ProgramFiles\Python\TestValid\Test2.py", line 31, in email
message = await bot.wait_for(on_message)
File "C:\Users\Tim Oliver\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 980, in wait_for
ev = event.lower()
AttributeError: 'function' object has no attribute 'lower'```
event.content
and how to mention this?
Is it possible to do like on first button click the bot should respond with 1
And on second button click by the same user send 2
Pretty cool
buts ' not "
That's the issue
uh, how? xD
uhm?
use json.dumps instead of just str, dictionaries and JSON are not the same
Result = json "{'custom_prefix': 'm!', 'on_mention': 'true'}"
xD
i told you to use json.dumps lol
json.dumps(data)
!d json.dumps
json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* to a JSON formatted [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table). The arguments have the same meaning as in [`dump()`](https://docs.python.org/3/library/json.html#json.dump "json.dump").
Note
Keys in key/value pairs of JSON are always of the type [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"). When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, `loads(dumps(x)) != x` if x has non-string keys.
mention what?
mhm
@commands.Cog.listener()
async def on_guild_join(self, guild):
with open("./guild/guildID.json", "r") as raw:
data = json.load(raw)
with open("./guild/{}.json".format(guild.id), "w") as raw:
json.dumps(data)
rip
why do you need to write everything in json, if it's not a secret?
json isnt used for storing secrets lol
Pydroid is how
?
Lookup on the google store
Bruh you told 24/7
#965291480992321536 ahem
@client.command()
async def meme(ctx):
async with ctx.typing():
subreddit = reddit.subreddit("memes")
all_subs = []
top = subreddit.top(limit = 50)
for submission in top:
all_subs.append(submission)
random_sub = random.choice(all_subs)
url = random_sub.url
name = random_sub.title
author = random_sub.author
upvotes = random_sub.score
if random_sub.is_reddit_media_domain and not random_sub.is_video:
em = discord.Embed(title = name)
em.set_image(url = url)
em.set_footer(text= f'''from r/memes by {author} | {upvotes} upvotes''')
await ctx.send(embed= em)
i am using if random_sub.is_reddit_media_domain and not random_sub.is_video: so that it sends on images and gifs, but the problem is that the bot is reposting same memes frequently :<
anyone with a fix?
also, are there buttons available on discordpy?
yep
says it all, define bot s.m.h
i need my prefix too π
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
enable intents from dev portal
Okay
https://discord.com/developers/applications > choose app > bot
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
how to import them
install discord_components discord.py 2.0 first
lemme get thr link rq
i tried
from discord.ui import Buttons
a
still having error
nice ghost ping
what error though
guys i have no issues but my bot says: Kyiv has been unbanned. when i dont even have the thing anywhere in the code
is this^^ just what happens normally
did you type it before, then remove it after
or it just says that and you never ever typed that ever in your life
why cant i
i had it before and saved but then removed
most likely you forgot to restart bot
did you install dpy 2.0?
how do i install it
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, id: discord.User):
try:
await inter.guild.unban(id)
except discord.HTTPException:
await inter.response.send_message('Unbanning Failed')
else:
await inter.response.send_message(f'Unbanning Has been Successful for {id.name}')
``` this is my full code, when i use it, it still shows unbanned {user}
.-.
try:
# // Generating Token
for i in range(arg):
newToken = random_string(randint(16,20))
sql = ("""INSERT INTO unusedkeys(storage) VALUES("%s")""", (newToken))
cursor.execute(*sql)
connection.commit()
token.append(newToken)
token = "\n".join(token)
await ctx.message.reply(token)
except:
await ctx.message.reply("There was an error generating the key(s)")
I'm trying to execute this code but I keep getting this error pymysql execute() takes from 2 to 3 positional arguments but 61 were given someone please help
Hey ashley hru
I sent you TWO links earlier, did you even read what was written in that message?
oh i already did that thing
Driod
I'm good, you good?
yes now you can use Button and View, it's jus getting inderlined 'cause they arent used anywhere in your code yet
Button
does anyone know how to delete a command in discord.py?
bot.remove_command("your command")
tysm
u can read this in
!d discord.ext.commands.Bot.remove_command
remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to remove aliases.
Changed in version 2.0: `name` parameter is now positional-only.
thanks :)
;-; thanks alot
uri for what
which one should i remove ;-;
Both
If I wanted to host a small, private bot on a raspberry pi, what model would be best?
A 3B/B+ would probably suffice. I use a 4B and it does more than enough
Alright, thanks
Ok ty
Add intents in your commands.Bot bracket
why
...
it used it work without intents
commands.Bot parameter ok
intents are required in dpy 2m0
2.0
AAAAAAAAAAAAAA
intents = nextcord.Intents.all()
async def getMutedRole(ctx):
roles = ctx.guild.roles
for role in roles:
if role.name == "Muted":
return role
return await createMutedRole(ctx)
@bot.command()
async def mute(ctx, member : discord.Member, *, reason = "Aucune raison n'a Γ©tΓ© renseignΓ©"):
mutedRole = await getMutedRole(ctx)
await member.add_roles(mutedRole, reason = reason)
embed = discord.Embed(title="β
succès", description=f"{member.mention} a été **mute** !")
embed.set_thumbnail(url = "https://images.emojiterra.com/mozilla/512px/1f507.png")
embed.add_field(name = "Raison", value = reason)
await ctx.send(embed = embed)
how i can fix this error ?
Giving the bot permissions
It already has all the permissions
The bot's top role needs to be higher than the role you're adding and higher than the top role of the member
Sounds good bb
i get ads in YouTube and now discord bro
Lmaoo

okay thanks
Danny abandoned it
are you using internet explorer
which discord updates are you referring to
the next ones
^^
that gist was made a very long time ago and is not relevant anymore
6 march?
Yeh thats old news, Discord.py 2.0 will be around for sometime now, nothing announced in the discord.py server.
was false alert
import discord
client = discord.Client()
keywords = ['helios', 'wtf', 'elf', 'grim']
@client.event
async def on_ready(message):
for i in range(len(keywords)):
if keywords[i] in message.content:
for i in range(10):
await message.channel.send("**SPAMMMM**")
client.run('Token')
help pls!
Issue?
!d discord.Member.kick
await kick(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick "discord.Guild.kick").
You want to kill all members in your server?
nvm i have figured it out
sorry for the disturbance!
Kick them all
All good
oh wait
i need help in executing the message
like the bot isnt working
I mean.. okay. You can loop through guild.members, and .kick() them. Make sure to add an asyncio.sleep(...) so you don't get ratelimited
umm no
guid.members is a List[discord.Member], so you'll have to iterate over
for unlucky_member in guild.members:
await unlucky_member.kick(reason='coz u are in the list')
So when the cmd is executed it would kick all members??
also why kick but not ban?π
What would ban be?
yeah
π
^
u cant join back the server unless a mod unbans u
also discord ip bans so u can only join the server even with another alt if u only use vpn in short time
.ban() instead of .kick()
all members? guild.delete()
Okay thankyou @shrewd apex
lmao
mass kick/ban will ban/delete ur discord account as this is form of nuking and is against tos
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
await ctx.send(numb, delete_after=60)
email()
why cant i run a function like this
@slate swan your missunderstanding why im asking for those type of commands.
Its just for a moderator command smh
π
why is email() there
runs a function that sends a email
why would i use discord to send a email
theres prolly a function to send mail
Fr
unique
@slate swan
werd problems need weird solutions
this could work with a temp mail api and u could use to verify for websites
for unlucky_member in guild.members: await unlucky_member.ban(reason='goodbye !') says undefined variable guild
NO it took me 1 hour to find a tutorial that was not out dated to send a email
I need email method please
@shrewd apex
mailtm
fetch ur guild
@bot.command()
async def email(ctx):
await ctx.message.delete()
await ctx.send("Sending Email...", delete_after=3)
await ctx.send("Code:", delete_after=60)
await ctx.send(numb, delete_after=60)
email()```
oh my god
Wym? @shrewd apex
i thaught i copyed my pass on that that scared me for a second
why cant this work
c:\Tims_ProgramFiles\Python\TestValid\Test2.py:48: RuntimeWarning: coroutine 'Command.call' was never awaited
email()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
that is the error i get
it's expecting an await I think, but isn't that just going to run the bot command? You shouldn't call two functions the same thing, no?
await unlucky_member.ban(reason='coz u are in the list') indentation error, but its indented...
are you using repl
good i dea i should just transfre everything in email to the first function
Pydroid3
IT WORKED?????????????
not familiar with Pydroid3
I'd unindent everything and re-indent it. It could be that you've mixed tabs and spaces together which is a nono
that's unrelated to the indentation error so π€·
no
that would too easily be abused
for obvious reasons no
looping through the member list and mass banning would almost certainly hit rate limits too
maybe scrape user ids and do it
ye
proxies?
Can you send a example??
no lol
just need that cmd for a moderator command π
ur cmd is not allowed
Why?
mass banning = bad
mass ban = easy api ban
if its repetitive task then discord perm ban
You could also get yourself banned from using Discord altogether, its more of a malicious activity then a moderation tool, I mean why would you need a mass ban for moderation? Just a normal ban is sufficient. What your asking is just sus.
thats what im sayin
Dont understand why they keeps asking, its literally a form of malicious activity and against ToS. There is no other reason for it lol.
guild=ctx.guild role = discord.utils.get(guild.roles, name = "@everyone") await role.edit(permissions = Permissions.all()) anyone know how to fix?
yeah nice edit buddy
i saw the while loop now please stop the conversation.
!rule 5 1
1. Follow the Python Discord Code of Conduct.
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
:x: Invalid rule indices: 69
spam pinging the everyone role is a part of moderation?
interesting.
Yes.
Its legit for a party event for my server.
I dont get what the issue is.
it just spams it for a couple seconds
idc, please take your conversation else where.
Ok
You're probably trying to make one of those youtube discord server event bots. But that's technically not allowed.. so yea
Yeah i am
breaking discords tos and trying to get a way with it wont work here especially when youre clearly trying to nuke a server with horrible code.
