#discord-bots
1 messages ยท Page 747 of 1
dies what
Just saying their API might be very slow which may cause the blocking of the whole bot, better use aiohttp
typehint pls :v
You could use nested list
if len(r) > 0:
voted_usernames = [i['username'] for i in r]
And then enumerate it to add fields
async with aiohttp.ClientSession() as cs:
async with cs.get('https://top.gg/api/bots/879000165757890570/votes') as r:
res = await r.json()
uh, how about dis?
This is good
lemme try :v
Also have you tried printing the response?
nop
@zealous dagger
pip install git+https://github.com/Rapptz/discord.py```
Iirc
Add -U flag as well
@vale wing
@bot.command()
async def last1000voters(ctx):
name = ctx.author.id
if name == 828182019841327115:
async with aiohttp.ClientSession() as cs:
async with cs.get('https://top.gg/api/bots/879000165757890570/votes') as r:
res = await r.json()
le = len(list(res))
em = discord.Embed(title="last 1000 voters", description="", colour=ctx.author.color)
for i in range(le):
em.add_field(name=str(i + 1), value=f'{res["username"][i]}', inline=False)
await ctx.send(embed=em)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'username'
waht
@small igloo print the res
k wait
Try my method
is dat will giev a list of usernames or just a single one
not understand
So did you get it?
dies
Lmao
but i friggin hav bot registered in top.gg :l
what
async with aiohttp.ClientSession(headers={'Authorization': 'top.gg token'}) as session:
...```
still need help T^T
Just one thing to note; you're over writing the built-in list
Better name the variable differently, list is a builtin
You are trying to make a function to provide to command_prefix param right?
i was trying to do jackpot but why it only gives "not jackpot"
it was for bot ofc
for example ๐, ๐, ๐ but it prints not jackpot
Because maybe your condition is wrong
Also your second condition is weird, I am sure you can't use it like this
!e
print('s1' == 's2' == 's3')```
@vale wing :white_check_mark: Your eval job has completed with return code 0.
False
Yeah
This a weird lol I got confused

Ok forget it it's weird you should compare it using any or or
ok
if not any([
final[0] == final[1],
final[1] == final[2],
final[0] == final[2]]):
print('not jackpot')```
@client.command()
async def warn(ctx, member: discord.Member = None, *, reason=None):
id = member.id
if collection.count_documents({"memberid": id}) == 0:
collection.insert_one({"memberid": id, "warns": 0})
if reason == None:
await ctx.send("Please mention a reason!")
elif member == None:
await ctx.send("Please mention a user!")
warn_count = collection.find_one({"memberid": id})
count = warn_count["warns"]
new_count = count + 1
collection.update_one({"memberid": id}, {"$set": {"warns": new_count}})
await ctx.send(
f"Warned {member} for {reason}. They now have {new_count} warnings.")```
Error : Ignoring exception in command warn:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 179, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 31, in warn
id = member.id
AttributeError: 'NoneType' object has no attribute 'id'
Its a basic warn with mongodb
you have to define it in the command parameters i guess
async def test(member : discord.Member)
did you do this?
Why'd you add default value to member
i did
Yea I saw sorry
Default as in None?
remove the = None
I don't remember, lemme search
Does py elif member == None: await ctx.send("Please mention a user!")
this work if i remove the None
That is error handling
It has to be the first then
use on_command_error
But don't set default value to necessary argument for god's sake
alright!
thanks for the help both of you!
๐
!d discord.on_voice_state_update @hidden hazel
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
Could you show code?
You used replit, this happened.
One reason why you should not use replit:
They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
@config.command()
async def unwhitelist(self,ctx, channel: discord.TextChannel = None):
if channel == None:
channel = ctx.channel
unwhitelist = {"channel" : channel.id}
if not unwhitelist:
return await ctx.send("This channel is not whitelisted")
await self.coll.delete_one(unwhitelist)
await ctx.send(f" Unwhitelisted <#{channel.id}> for typeracer")
Even though the channel isnt in my mongo collection it still says Unwhitelisted <#{channel.id}> for typeracer why?
That happened to me
Just wait a few hours
You just ran the bot too much
In the mean time you can keep on coding
listener()
^
Hi, so i have an economy bot with a deposit command (sqlite3)
Any idea on how to put a limit that your bank balance cannot be more than say 500k?
you could, in the command check if the users balance is 500k or more
But that wouldnโt be the best because that could mean the balance COULD go over 500k in the database
and we want the table to be created with a maximum of 500k for the balance
Just check when the money is being deposited
^
hello
@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
minutes, seconds = divmod(remainder, 60)
channel = bot.get_channel(931185915932577862)
try:
await channel.edit(name="test55")
except Exception as e:
print(traceback.format_exc())
war_update_time.start()
im trying to make it where the bot changes it name every 10m in the long run but every 1m now for I can test if the change work
but it seems to not be working any idea
i am aware of the discord rate lmimt being of 10m
Have you checked if the loop works
Did you start the loop?
the loop work for this other code where i need a loop at
yh the loop starts with war_update_time.start()
what event do I use to check if a member has changed their status?
Not sure
@bot.event
async def on_member_update(before : disnake.Member, after:disnake.Member):
if after.roles != before.roles:
guild = before.guild
channel = disnake.utils.get(guild.channels, id=930112620407697429)
role_id_list = #a role list
role = set(before.roles) - set(after.roles)
if isinstance(role, guild.premium_subscriber_role):
if booster_color := disnake.utils.find(lambda r: r.id in role_id_list, after.roles):
await member.remove_roles(booster_color, reason="User stopped boosting the server")
embed = disnake.Embed(description=f"{member.mention} {str(member)} Stopped boosting the server!\nRemoved role: {booster_color.mention}")
embed.set_thumbnail(url=after.avatar.url)
embed.set_footer(text=f"{after.id}")
await channel.send(embed=embed)
Does anyone see anything wrong here?
!d discord.on_user_update
discord.on_user_update(before, after)```
Called when a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") updates their profile.
This is called when one or more of the following things change:
โข avatar
โข username
โข discriminator...
this, perhaps
on_member_update or on_user_update?
For some reason it does have a status
I don't think it matters in terms of status
oh wait status as in idle, do not disturb?
also, anyone mind looking at this
Doesn't object you are searching in go as a first arg?
!d discord.utils.find
discord.utils.find(predicate, seq)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") whose name is โMightyโ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.9)") due to the fact it stops the moment it finds a valid entry.
Ok no
please use a placeholder instead of the invite link
Hold up you have := there
Is it even a thing
i think this is unnecesary if after.roles != before.roles:, it will never be same
for a vanity check, does this work?
@bot.command
async def on_member_update(before:discord.Member, after:discord.Member):
if after.status != before.status:
if after.status == "my vanity":
#do stuff
I guess the status is not a string, it is discord.Status
youre sus
what
i mean i dont think it triggers on_member_update, if nothing has changed
!d discord.Member.status
property status: discord.enums.Status```
The memberโs overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
Yeah it's not a string
how do i check for it?
!d discord.Member.activity most likely
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
I need to check this by myself, never had a need to fetch user's status
why u wanna set booster role? its handled automaticly
take ur time
im a little confused on that
what do you mean set
hi
i'm new to py and discord py bot develop
trying to create a nice bot for myself
i want to create a organize space for the work and i heard of something called Commands Handler and event handler,
how im bringing this into my project and acctually implementing this?
If you are new to python overall then starting learning it from discord bot is a bad choice. It is an advanced asynchronous application which requires intermediate knowledge to implement
I'm not new to programming though, I just have to learn a little bit of syntax and ill be at the right level
What languages do you know else
java,C# most back-end languages that I use usually
Nice
Then I can recommend you this tutorial
https://vcokltfre.dev
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
you can make a discord bot with java
anyone know how to check for a member status?
i know, i did on C# but i want to get better at py
cool
JDA library for developing bots on java is very ugly complicated imo
C# also..
yea lol
Best languages for creating discord bots are python, js and kotlin I'd say
At least they have normal wrappers
you have like 200 lines of code for just a ping command and a running bot
async def on_message(message):
if message.content.lower() == "olorandom":
rand = random.randint(0,15)
await message.channel.send("Choose a number from 1-15")
if message.content.lower() == rand:
await message.channel.send("good job")
if message.content.lower() != rand:
await message.channel.send("wrong try again")```
can someone explain why no work
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
@left crater what are you trying to do here?
@vale wing can you help me with the handler?
Also you don't have process_commands here, add it or use a listener
the generates a random number and the user has to guess it
if wrong then it will say wrong
how do i rename a discord voice channel
And seems like you are implementing commands in on_message event which is bad practice
should i use ctx
!d discord.VoiceChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
@left crater check this out as well
i wonder why mien doesnt work then
Have you tried that tutorial?
client.fetch_user() only working in functions with @client.command() decorator
not yet, i will now
Ratelimit or discord smoking grass, I had the same issue long time ago

How do you define client
Then you haven't got it properly
@bot.event
async def on_member_update(before, after):
if before.status is discord.Status.WHAT and after.status is discord.Status.WHAT:
client = commands.Bot(command_prefix = "~", help_command = None, debug_guild = 12893413483)
@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
print("hi1")
war = await client_coc.get_current_war('#2YY0LGG9G')
hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
minutes, seconds = divmod(remainder, 60)
channel = client_main.get_channel(931185915932577862)
try:
print("hi2")
await channel.edit(name="test55")
except Exception as e:
print(traceback.format_exc())
war_update_time.start()
``` this is my code i get into both blocks or w.e
so it's something with the channel.edit that doesnt work
and im not sure why, it say n onetype object has no attribute edit
How is your client defined
client_main
im guessing you mean this
client_main = commands.Bot(command_prefix = cfg.config['bot_command_prefix'], activity=discord.Activity(type=discord.ActivityType.watching, name="for API updates"), intents = discord.Intents.all())
Ok this is right
yh im pre lost and confused why it saying edit isnt valid or w.e
@tasks.loop(seconds=3)
async def status_role():
guild = bot.get_guild(ID)
role = get(guild.roles, id=id)
[await member.add_roles(role) for member in guild.members if member.activities[0] and 'vanity' in member.activities[0].name.lower()]
?
im checking for a member status change
but shudnt it be in the on_member_update() event?
@steel void what happened
!d discord.on_presence_update is what u r searching for (:
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
basically whenever I use await channel.edit(name="test55") to edit the channel name I get an issue saying nonetype object has no attribute edit
That means channel is None
Mind showing where u r defining it?
channel = client_main.get_channel(931185915932577862)
i just rechecked the id, it is correct, but it is a voice channel
if that makes a difference
No
343944376055103488 This channel id
931185915932577862 your id
tyyt
U mean the different number series? @cloud dawn
No that his is shorter
i coped it directly
Aaaah gotcha
from the copy id function twice
This channel is what 3.5 years old unless his is like 5 years or older
and whenever i do <#channelid> https://xbb.speedygoat.net/dUJU7/KewOfofU73.png this appears so it is a valid channel
afaik all id's are 18 in lenght
so any ideas?
for what?
on my issue
You used your mouse to copy the id?
yh
sorry i just joined the chat what is it?
right clicked on channel
Even voice channels have an ID of 18 digits
@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
print("hi1")
war = await client_coc.get_current_war('#2YY0LGG9G')
hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
minutes, seconds = divmod(remainder, 60)
channel = client_main.get_channel(931185915932577862)
try:
print("hi2")
await channel.edit(name="test55")
except Exception as e:
print(traceback.format_exc())
war_update_time.start()
``` this code i get this error https://images-ext-2.discordapp.net/external/d_h0eNu4LH4LFaX-0LITU2Y7_1VCc1XBFp6SKwV5vH0/https/xbb.speedygoat.net/dUJU7/COyePaYe19.png
!e ```py
print(len(str(931185915932577862)))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
18
Lol
!e ```py
print(len(str(343944376055103488)))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
18
@steel void can the bot "see" the channel?
yeah the bot has admin of the server
maybe try to fetch the channel and confirm the type of the channel
Could you fetch the channel?
Yea try fetching
how would i do that
!d discord.Client.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/master/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.get_channel "discord.Client.get_channel") instead.
New in version 1.2.
channel = client_main.get_channel(931185915932577862) or await client_main.fetch_channel(931185915932577862)
Just like u r using get_channel, but with an await
Yea best code
Acc made a function for that, idk why discord didnt lol
i forgot how to define a bot var lol
Acc?
actually
!d discord.Client
class discord.Client(*, loop=None, **options)```
Represents a client connection that connects to Discord. This class is used to interact with the Discord WebSocket and API.
A number of options can be passed to the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client").
Ah my bad
bot var
disnake, like commands.bot or smth
sends client
lmao
@bot.event
async def on_presence_update(before, after):
if before.activity != after.activity:
if after.activity in ["vanity 1", "vanity 2"]:
#do stuff
works?
!d disnake.ext.commands.Bot
class disnake.ext.commands.Bot(command_prefix=None, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`disnake.Client`](https://docs.disnake.dev/en/latest/api.html#disnake.Client "disnake.Client") and as a result anything that you can do with a [`disnake.Client`](https://docs.disnake.dev/en/latest/api.html#disnake.Client "disnake.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.GroupMixin "disnake.ext.commands.GroupMixin") to provide the functionality to manage commands.
Sure, ig
I just subclassed the bot so i don't have bot "vars"
shouldn't it be status instead of activity
Also subclassing prevents type errors
!d discord.Member.activities
The activities that the user is currently doing.
Note
Due to a Discord API limitation, a userโs Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.
Looks cleaner aswell :3
!d discord.CustomActivity is yr status
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activityโs hash.
str(x) Returns the custom status text.
New in version 1.3.
Facts, but i dont wanna teach beginners how to subclass, so botvars better :DDD
send code lol
send(embed=embed), not send(embed) @left crater
Coding a slash bot rn looks pretty clean and tbh works very well i don't even have an error handler.
Why no error handler?
a, a, slash bot?
Cz there are no errors like MissingPerms and stuff?
That's the thing they just don't care.
FACTSSSSS
Yay
what are those?
Basically, a way of organising commands
https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
https://stackoverflow.com/questions/53528168/how-do-i-use-cogs-with-discord-py
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
.bm 931204919669698590
I denied my bot everything even send messages when i did slash it still sended me a message. Looks like slash isn't a message or smth.
what u mean with botvars?
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
It's a webhook
Yes
Ok thanks
!d discord.ext.commands.Bot.check is there BTW @dreamy sluice
@check```
A decorator that adds a global check to the bot.
A global check is similar to a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is applied on a per command basis except it is run before any command checks have been verified and applies to every command the bot has.
Note
This function can either be a regular function or a coroutine.
Similar to a command [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check"), this takes a single parameter of type [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") and can only raise exceptions inherited from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError").
Example...
I prob need an error handler with some commands but for now the only error i've got so far is a charmap error.
so I just do Cog.Bot.check?
That's more of a backend error haha
and u mean basicly make a class n put self.bot=commands.Bot()
Ye emoji in my console lmao
ohh
bot = commands.Bot(...)
@bot.check
async def check():
. . .
@bot.event
async def on_presence_update(before, after):
if before.activity != after.activity:
if after.activity in ["vanity 1", "vanity 2"]:
guild = bot.get_guild(914533133179813919)
role = discord.utils.get(guild.roles, id=931191386076749896)
#how do I add the role to that specific member?
It sucks when those errors come BTW
I know how to do a regular check, but how do I implement that in a chord?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Remember before and after are Member objects
!d discord.ext.commands.Cog.check
No documentation found for the requested symbol.
Emoji's suck in general that's why i switched to postgre since some ppl setted their prefixes as a laughing emoji. Well now they can lmao.
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
Weird that it's named cog check, not check
It was given as cog_check in documentation too
Well it's also bot_check so consistency is there ig
Yea ik
What have you been working on hunt?
Well yea, but cog.check seems.... more readable than cog.cog_check imho
Ways to hunt y'all down Eh just a project with a friend of mine (NOT related to discord)
:3
O-o
๐โโ๏ธ isnt cog.check a decorator , and cog_check a method
nvm cog.check does not exist
Yea lol
I actually wanted to replicate the eval of python discord
That's too complex for my IQ Level
appears the eval command is combined around 2500 lines
I need to host my own API to that shit
holding back my urge to send a meme here
If it is topical go for it lol
Let's edit it to run it locally :DDD
It's the MOST OFF TOPIC MEME for this channel
You can but you need to use docker and me no like docker
K8 
And when you got the API working you need to extract the code from the command itself that has a lot of hard coded checks.
Facts
does set(before.roles) - set(after.roles) on an on_member_update return a role object or a set?
ah yeah
- and + operators always return the same object type
Ok, meme incoming (sorry)
how do I check if a member has a specific role?
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [โ@everyone](mailto:'%40everyone)โ role.
These roles are sorted by their position in the role hierarchy.
Get a role object then use the in operator
me too
Wait, that's my-
our meme
yea yea
what if i need the id?
of the role
get_role(role_id, /)```
Returns a role with the given ID.
This?
let me try hollyp
appreciate it
(:
How often do on_ready async functions restart
Depends.
on what
Yeah but sometimes it does it in middle of runnig
depends on network i guess
internet
And that happens
-> on startup
-> on reconnection
-> on restart
It's very random.
No
reconnections aren't really predictable.
Yea, but that's when on_ready is called
Thus can be very random
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Oops wrong ping
im completely lsot on waht you guys sugggested for me
i thought maybe it was cause it was running before the bot was up and i added wait_until_ready but still the edit error
Damn discord making our work difficult
Yea... That's a common issue. Tasks can start before the bot starts up
yh still havent changed nothing sadly
Mind showing me the code?
updated code
@tasks.loop(minutes=1)
async def war_update_time(minutes=1):
try:
await client_main.wait_until_ready()
print("hi1")
war = await client_coc.get_current_war('#2YY0LGG9G')
hours, remainder = divmod(int(war.end_time.seconds_until), 3600)
minutes, seconds = divmod(remainder, 60)
channel = client_main.get_channel(931185915932577862)
try:
print("hi2")
await channel.edit(name="test55")
except Exception as e:
print(traceback.format_exc())
except Exception as e:
pass
war_update_time.start()
Hmm
ii thought maybe it was cause of the task starting before bot but it doesnt appear so
Yea that's a common issue ngl
so im completely lost
Still the NoneType issue?
What is this try except?
How do I send a message to channel on bot load?
Lmao
!d discord.TextChannel.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
I got that part.
I am talking about when the bot first turns on, I want it to send a message
!d disnake.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientโs internal cache is all ready.
wdym its just for the wait until ready event to get triggered
like in the console?
or in a channel?
Did u try fetching the channel?
no i read the documentation you guys sent but im confused wid it
Uhh, just try fetching the channel
@drifting arrow
@maiden fable it didn;t work
async def on_ready():
print("Bot is ready!")```
@bot.event
async def on_presence_update(before, after):
guild = bot.get_guild(914533133179813919)
role = discord.utils.get(guild.roles, id=931191386076749896)
if before.activity != after.activity:
if after.activity in ["vanity 1", "vanity 2", "/uploaders"]:
vanity_embed = Embed(description=f"{after.mention} thx 4 repping **vanity** ", color=0x0f0f0f)
channel = bot.get_channel(931191146099658822)
await after.add_roles(role, reason="Repping Vanity")
await channel.send(embed=vanity_embed)
try:
await after.send("appreciate it for repping **vanity**. you were given the vanity role")
except:
pass
else:
if role in after.roles:
await after.remove_roles(role, reason="removed vanity")
shud it be after.status?
What is that try/except?
attempting to dm a member
after it has sent its messages in the desired channel, if it cannot dm a member, it passes
what shud I do?
!tags
!except
A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.
try:
number = int(user_input)
except ValueError:
print("failed to convert user_input to a number. setting number to 0.")
number = 0
You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.
try:
number = int(user_input)
item = some_list[number]
except:
print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")
For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.
shud I print instead?
Oh it's in here
No you should specify the error
The error that you get if you get an exception?
if its the try statement, then it shudve worked until the try statement
but it didn't
idk the error I get when a user cannot be dmed
discord.Forbidden
except discord.Forbidden?
try it out
my code isn't working
its supposed to check my status
then send a message to a channel
then give a role
then dm the user if possible
it doesn't do anything
on_presence_update isn't a thing
?
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...

oh weird it wasn't showing up for me, nevermind
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
do you have the necessary intents
intents = discord.Intents.default()
intents.members = True
intents.presences = True
Did you pass them in to the bot constructor?
pass the intents?
Show me your bot constructor
omds
i figured it out
lemme add it
bot = commands.Bot(command_prefix="$", intents=intents, owner_id=909799519477190656)
nvm i alr have it
What about dev portal
might aswell do discord.Intents.all()
These are privileged intents that need to be turned on at the developer portal too
It's gonna error out anyways if u dont turn them in discord dev portal, but in the code
What is the best way to hide commands with a slash bot?
I don't think u can lol
i have it on
presence and members
#discord-bots message this would work
if the role has admin perms it'll work
no need to check for the role itself thats a security risk
@sacred sigil are your messages getting deleted?
if so it's bc you have a server invite in the code
remove that and try again please
@bot.event
async def on_presence_update(before, after):
guild = bot.get_guild(914533133179813919)
role = discord.utils.get(guild.roles, id=931191386076749896)
if before.activity != after.activity:
if after.activity in ["vanity 1", "vanity 2", "vanity 3"]:
vanity_embed = Embed(description=f"{after.mention} thx 4 repping **vanity** :packed:", color=0x0f0f0f)
channel = bot.get_channel(931191146099658822)
await after.add_roles(role, reason="Repping Vanity")
await channel.send(embed=vanity_embed)
try:
await after.send("appreciate it for repping **vanity**. you were given the vanity role")
except discord.Forbidden:
pass
else:
if role in after.roles:
await after.remove_roles(role, reason="removed vanity")
yeah i apologize abt that
i had to remove my vanity
Is there a function that awaits users response?
I want my bot to send a question to a user in a DM (already got this part)
and now I want the bot to await a response before it continues
Like an input. Is there any functionality for this?
yes, it's called client.wait_for
how do i delete the last, lets say 100 messages from a certain user?
in a text channel?
And only those
channel.purge is what you're looking for
with a check
!d disnake.TextChannel.purge
await channel.purge(amount , check = lambda m : m.author = user)```
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.read_message_history "disnake.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting botโs messages...
the check is a bit hacky, since it'll check 100 messages, instead of 100 messages from a certain user, so I hope you're happy with that
no, the last 100 messages from that user
I guess the around kwarg in disnake fixes that lol
anyone?
you didn't ask a question...
@sacred sigil Your message got deleted I guess, ask the question again
like, if i want to delete my last 10 messages, i loop through the last 10 messages that were not by me. But the last one IS MINE, so it deletes that messages instead of my last 10
What I want to do:
- check member's status
- if it changed, check if its my vanity
- if its my vanity, send an embed to a channel, give the member a role, and send them a dm if possible
if it changed, and they have the vanity role, remove the role since they are not repping my vanity
- if it changed, check if its my vanity
just check the documentation of that function
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
Status, not activity
can I guess what you did wrong?
have you debugged the code even a bit, yet?
The custom status
and .status if you mean the idle , online thing
how do i get the last 10 messages from a user, like ctrl+f in the ui of discord
Ah nvm
What I want to do:
- check member's status
- if it changed, check if its my vanity
- if its my vanity, send an embed to a channel, give the member a role, and send them a dm if possible
if it changed, and they have the vanity role, remove the role since they are not repping my vanity
- if it changed, check if its my vanity
im sure they mean activity , reference from their code above
^^^
yeah mb
@bot.event
async def on_presence_update(before, after):
guild = bot.get_guild(914533133179813919)
role = discord.utils.get(guild.roles, id=931191386076749896)
if before.activity != after.activity:
if after.activity in ["vanity 1", "vanity 2", "vanity 3"]:
vanity_embed = Embed(description=f"{after.mention} thx 4 repping **vanity** :packed:", color=0x0f0f0f)
channel = bot.get_channel(931191146099658822)
await after.add_roles(role, reason="Repping Vanity")
await channel.send(embed=vanity_embed)
try:
await after.send("appreciate it for repping **vanity**. you were given the vanity role")
except discord.Forbidden:
pass
else:
if role in after.roles:
await after.remove_roles(role, reason="removed vanity")
u wrote the code before, what happened to that
yea this.... what happened
so no one is gonna talk about the incorrect event name?
It is correct tho
a different library probably
!d discord.on_presence_update
discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their presence.
This is called when one or more of the following things change:
โข status
โข activity
This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
I copy and pasted it to make sure
its not doing anything
this would only work IF he got v2+
yea
I'd check first if his event even triggers
you can check memberactivity.name it will return the user's status in a string form for example for me it will be slash commands ( look at my status )
if u r using dpy 1.7, then use on_member_update @sacred sigil
you can then use if vanity in the_activity_name
he also needs some intents enabled, you guys are skipping some steps
bro, he has both members and presences smh
I only started reading from where he shared his code
he has been asking about the code since like 30 min or smth, soooooooo
feelsbadman
i think I have the latest ver
if so how do I change it?
do I change the event name thats it?
such as?
just change the event to on_member_update?
yea...
the same
try printing discord.__version__
!d disnake.TextChannel.delete_messages
await delete_messages(messages)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes a list of messages. This is similar to [`Message.delete()`](https://docs.disnake.dev/en/latest/api.html#disnake.Message.delete "disnake.Message.delete") except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If itโs more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission to use this.
nice
!d discord.TextChannel.purge is better @quaint epoch
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Examples
Deleting botโs messages...
Ouch
so, delete_messages and .purge both have bulk options, and both support only 100 messages for bulk delete?
in the last 14 days?
yea
oh, well im using delete_messages instead
both work just as well for me
okay
but thanks
how shud I print it
1.7.3
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
โข nickname
โข roles
โข pending...
i did lol
one sec
@bot.event
async def on_member_update(before, after):
guild = bot.get_guild(914533133179813919)
role = discord.utils.get(guild.roles, id=931191386076749896)
if before.activity != after.activity:
if after.activity in ["v1", "v2", "v3"]:
vanity_embed = Embed(description=f"{after.mention} thx 4 repping **v1** :packed:", color=0x0f0f0f)
channel = bot.get_channel(931191146099658822)
await after.add_roles(role, reason="Repping Vanity")
await channel.send(embed=vanity_embed)
try:
await after.send("appreciate it for repping **v**. you were given the vanity role")
except discord.Forbidden:
pass
else:
if role in after.roles:
await after.remove_roles(role, reason="removed vanity")
does py ctx.message.delete() have a reason param?
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleโs messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
or py ctx.message.channel.delete_messages() have a reason param
As you can see, no.
oh alr
how can we create buttons in disanke without classes
!d disnake.TextChannel.delete_messages
await delete_messages(messages)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes a list of messages. This is similar to [`Message.delete()`](https://docs.disnake.dev/en/latest/api.html#disnake.Message.delete "disnake.Message.delete") except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If itโs more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have the [`manage_messages`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_messages "disnake.Permissions.manage_messages") permission to use this.
button = discord.ui.Button()
It will take all the kwargs you would use with the class
disnake*, I'm getting stuck at some places
Disnake forked that from discord.py so it remains same
Send the code and issue u face
?
@slate swan
make a view object , and add it in it
lemme send an example
view = disnake.ui.View()
button = disnake.ui.Button()
view.add_item(button)
await send(view=view)```
ohk lemme try
getting an error 2022-01-13T16:52:44.189475+00:00 app[worker.1]: /app/.heroku/python/lib/python3.9/asyncio/events.py:80: RuntimeWarning: coroutine 'Command.__call__' was never awaited 2022-01-13T16:52:44.189498+00:00 app[worker.1]: self._context.run(self._callback, *self._args) 2022-01-13T16:52:44.189499+00:00 app[worker.1]: RuntimeWarning: Enable tracemalloc to get the object allocation traceback This is the code py @bot.command() async def Google(ctx: commands.Context, *, query: str): button = disnake.ui.Button view = disnake.ui.View() query = quote_plus(query) url = f"https://www.google.com/search?q={query}" view.add_item(button(label="Click here", url=url)) await ctx.send(f"Google Result for: `{query}`", view=Google(query))
@slate swan
u didnt await something
await send(view=view)?
nah whats the Google thing?
for the query?
Yes
If its async you would need to await it
If its not async I wouldn't suggest you use it
but await what
removing view=Google(query) makes the command work but not adding the button
async def on_member_ban(self, member: discord.Member):
channel = self.bot.get_channel(814956709290049596)
if not channel:
return
await channel.send(f"{member} was banned!")```
when i ban someone nothing happens
because the view was named view , not Google
whats the quote_plus function>
hello
it replaces '' with '+'
makes sense , but your view class is named view , so it would be view=view
what is the variable for name + #tag
{ctx.author.name} only gives names not the # tag
Is anyone familiar with nextcord? I'm running into some issues with the slash_command function not registering any commands to my guild
isnt their slash command not stable apparently, i think ir ead where they said not to use it in production builds
yes in dpy
Hm, that's unfortunate. I got it to pop up really quick using the command from nextcord.ext.commands.Bot, but doing it withnextcord.Client yields nothing.
I'll try waiting to see if it pops up after a while
a lot of ppl i know went to pycord, someone said it only took them 1h to get everything working again since its very close to discord.py
I'll take a look at pycord then. Nextcord seemed nice cause I could just run my old stuff really fast, but I'd like to use slash commands lmao
pycord supports slash, i just heard a lot of good stuff about it, ima switch to pycord eventually
Yeah, I'd not use it in production currently, since we haven't fully tested it for production yet
we
I'm a nextcord maintainer lol
How many forks do u even contribute to ๐
2 
yea yea won't be surprised if more come out
That said, pycord wouldn't be my goto either, due to strange design choices, like making slash commands interact badly with type checkers, so I'd recommend disnake personally, which does have a shim that lets you keep the same imports if you want
And also has a better slash command implementation in general, but thats my opinion
Hmm
Is disnake a based on the old Discord.py?
Yup
Sick, I'll go look at that. Trying to find a good replacement
where do is tart with discord bots?
watch yt tutorials
so lets say
bad advice :/
I had a users ID how can I assign them with a certain role using the ID that is saved to a variable
why? Depends on what bot u want to make
More depends on the tutorial lol
it brings you closer how to setup the bot
^ there are a bunch of outdated tutorials
I'm having an issue with anime quote command of my bot. This is the code py @bot.command(aliases=['aq']) async def animequote(ctx, *,anime: str): if not anime: async with aiohttp.ClientSession() as session: request = await session.get('https://animechan.vercel.app/api/random') quotejson = await request.json() embed = disnake.Embed(title=quotejson['anime'],description=quotejson['quote'] , color=ctx.author.color) embed.set_author(name="Anime Quote") saidby = quotejson['character'] embed.set_footer(text=f"- {saidby}") await ctx.send(embed=embed) else: async with aiohttp.ClientSession() as session: request = await session.get(f'https://animechan.vercel.app/api/random/anime?title={anime}') quotejson = await request.json() embed = disnake.Embed(title=quotejson['anime'],description=quotejson['quote'] , color=ctx.author.color) embed.set_author(name="Anime Quote") saidby = quotejson['character'] embed.set_footer(text=f"- {saidby}") await ctx.send(embed=embed) This is how the sample json looks like json {"anime":"Naruto","character":"Naruto Uzumaki","quote":"If you don't like the hand that fate's dealt you with, fight for a new one!"} When I run it I don't get any error and command doesn't work
Do you have on_command_error event?
no
I'm not sure but smth with apis, smth like musci bot or economist :p
oh ooops
Also you should set default value of anime arg as without it it will raise MissingRequiredArgument and if it is provided if not anime will always be False
@boreal magnet
then it will only fetch for one anime
I mean
async def animequote(ctx, *, anime = None)```
well I started new aswell and I guess the best way to start in making a bot is by watching videos on how to set one up first, and then going to solve a problem one by one
@harsh stump
oh
k
they can set a default value and instead of if not anime, they can do if anime == default_value
I never watched a single youtube tutorial (they're too slow for me)
@honest shoal also make sure request goes properly
if you have no experience in coding or any of the discord api then you probably need it
it does
anyways, does anybody know how to generate images with code as input?
When I started learning discord bots I had like intermediate python knowledge, I could for example make a game with pygame or a pyqt app
So wasn't a big issue
thats great, I have some programming experience in general but no specific language
so I wanna sneak peak here slowly and I cant find a solution to my first problem ๐
There's PIL module
I don't remember how's it named on pypi tho
I dont actually need to edit an image specifically, its more like putting different png elements together to generate one jpg
it sounds basic but I didnt find any solution online
You can look how I have done it
https://github.com/Exenifix/CoreBot/blob/main/modules/image_generator.py
for example:
Make a simple variable called "Balance" and adjust the image to the count of your balance
will do
yeah it might be pretty hard to achieve but it looks great when its done
ok, so I was tired up and made the command simpler for now this is the code py @bot.command(aliases=['aq']) async def animequote(ctx): async with aiohttp.ClientSession() as session: request = await session.get('https://animechan.vercel.app/api/random') quotejson = await request.json() embed = disnake.Embed(title=quotejson['anime'],description=quotejson['quote'] , color=ctx.author.color) embed.set_author(name="Anime Quote") saidby = quotejson['character'] embed.set_footer(text=f"- {saidby}") await ctx.send(embed=embed) I'm now stuck with same issue again command doesn't work and no error
Yesterday there was a guy with similar issue and it turned out he had error handler that was eating the error, I am not saying you have exactly the same issue but are you totally sure you don't have any error handlers?
print ur quotejson also n see fi u even get json
quotejson = await request.json()
print(quotejson)
if no json ur embed wont work
but should get error
no result
then u need to investigate why ur json not working ๐
No I don't
@honest shoal add this to your code so we can 100% catch the error
@bot.listen('on_command_error')
async def error_handler(ctx, error):
raise error```
๐
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired
ssl verification is old n not valid for client
(serverside)
but throu my browser it is a valid ssl cert
i googled someone sais this i dunno
Go to discord.com with Internet Explorer (Ran as Administrator)
Click the lock on the top right
Click view certificates
Install one
and this
import ssl
try:
_create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
# Legacy Python that doesn't verify HTTPS certificates by default
pass
else:
# Handle target environment that doesn't support HTTPS verification
ssl._create_default_https_context = _create_unverified_https_contex
sheesh
try removing https:// from the url
i tried but got directed to https
wait who had the SSL certificate error?
me
in your code
he means try http:// instead of https://
request = await session.get(f'http://animechan.vercel.app/api/random/anime?title={anime}')
oke
didn't work, same Issue
How do I add a specific role using someones ID thats saved to a variable?
paying someone $10 any crypto
if they can dm a solution
!rule 9
doesn't matter, you aren't allowed to offer paid works here
also I don't get your ques.
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
@commands.Cog.listener()
async def on_reaction_add(self, reaction, user):
if user == self.client.user:
return
if reaction.message == self.message:
def check(m):
if m.author == user:
return m.content
await user.send("Please enter a description of the discord")
cheat_discord_description = await self.client.wait_for(
"message", check=check
)
await user.send("Please enter the link to the discord.")
cheat_link = await self.client.wait_for("message", check=check)
if 'https://discord.gg/' not in cheat_link:
await user.send('No cheat discord entered. Closing report.')
return
await user.send("Please enter the software type")
software_type = await self.client.wait_for("message", check=check)
await user.send("When was the last major update? YYYY-MM-DD preferably.")
major_update = await self.client.wait_for("message", check=check)
await user.send(
"Please enter a link to the website. If it has none, just say none."
)
cheat_website = await self.client.wait_for("message", check=check)
await user.send("Are there any hidden features?")
hidden_features = await self.client.wait_for("message", check=check)
await user.send("Thank you for the report. It has been submitted successfully.")
embed = discord.Embed(title="Cheater discord report")
mychannel = self.client.get_channel(self.reports_channel)
await mychannel.send(embed=embed)
How do I make this work for multiple users?
At the moment if 2 people react to a message at the same time, it just stops everything
Does it return any errors at all?
It did. reading it now it might be my code actually
Paste it here
Yep. It was my code
if 'https://discord.gg/' not in cheat_link:
await user.send('No cheat discord entered. Closing report.')
return
\o/ figured it out
You know you could use regex , this will work like ....
ew js
๐
its the wrong server
thats like saying oh yeah that looks like python when its clearly js
whats the point of all questions when u can type anything in every question theres no check of valid input at all
u deserve a ban
I have a question.
How can i require a role? (Like you must one of the roles on a list to run the command)
Sus
@frank tartanu can use decoration and has_role()
@commands.has_role() check this up in documentation
Because I dont need checks. If a user wants to fuck about they can get the boot
The only check is for discord link
@client.command(aliases=['s'])
@commands.has_role(name=roleList)
Like that?
tbh i dont know if it accepts a list, why i referenced to check docs
i looked at the docs too, thats why i asked my question hrere
seems like u can only have 1 role to be checked
either by id or name
so no list
but u can also check permissions
How do I get my bot to choose a line from a text file because so far all I'm getting is just a letter
@deep torrentthat Q is more for #python-discussion
ok
or google, "how to read specific line from a textfile"
maybe it has soemthing with .seek()
Maybe
@deep torrenthttps://www.kite.com/python/answers/how-to-read-specific-lines-of-a-text-file-in-python
Maybe you can answer this when I use the with open function I get this error
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape (test.py, line 46)
this examples reads 2 lines from 3 lines, 0 and 2 (aka 1st and 3rd)
Thank you
also for #python-discussion
Alright
error basicly sais u cant uncicode escape a byte
need string
or something that way
Is your bot sending more of the same messages than you were expecting? You are probably running multiple instances of the bot / program / process.
Typical cases for this are:-
โข Double clicking the file many times.
โข Running it through any IDE (most commonly Atom).
If you do any of these: don't. Please see ?tag dbc for how to properly run your Python code.
To correct this issue, please open your process manager (Task Manager on Windows) and kill the relevant Python processes. Then start the bot correctly, within your CLI.
Other common causes:
โข Using process_commands(Message) many times, or in a listener.
This can be corrected by not doing this in a listener, and only using this method once within the overriding on_message event.
yes u can be running same bot twice
make sure no bot is running n start 1
yeah like he said -> @magic ore
ye i had it running in both the shell and console (on replit)
keep getting this error dont quite know what it means
Command raised an exception: TypeError: tuple indices must be integers or slices, not str
You cannot use var["something"] on a tuple.
hi guys, my problem is this. i click the button, but the dadjoke link to facts, and dadjoke not work but use facts buttons
`@commands.command()
async def dadjoke(self, ctx):
await ctx.send(embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"), components=[[
Button(style=ButtonStyle.green, label="Next โถ๏ธ", custom_id="button1"),
Button(style=ButtonStyle.red, label="Stop ๐", custom_id="button2")
]])
@commands.Cog.listener()
async def on_button_click(self, interaction):
if interaction.component.custom_id == "button1":
await interaction.respond(type=7, embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"))
elif interaction.component.custom_id == "button2":
await interaction.edit_origin(embed=discord.Embed(color = 0x34568B, title="Dad Jokes Stopped! ๐ฎ", description=f"If you would like to use it longer, then push the next button or >dadjoke"))
@commands.command(aliases=["Facts","facts","Fact"])
async def fact(self, ctx):
await ctx.send(embed=discord.Embed(color = 0x990033, title="Did you know? ๐ฒ", description=f"{random.choice(facts)}"), components=[[
Button(style=ButtonStyle.green, label="Next", custom_id="button3"),
Button(style=ButtonStyle.red, label="Stop", custom_id="button4"),
]])
@commands.Cog.listener()
async def on_button_click(self, interaction):
if interaction.component.custom_id == "button3":
await interaction.respond(type=7, embed=discord.Embed(color = 0x990033, title="Did you know? ๐ฒ", description=f"{random.choice(facts)}"))
elif interaction.component.custom_id == "button4":
await interaction.edit_origin(embed=discord.Embed(color = 0x990033, title="random Facts Stopped!", description=f"If you would like to use it longer, then push the next button or >fact"))
`
Needs to be something like var[3]
ic
makes more sense thank you
Bascially, what's inside the [] can't be a string.
so like indexing a list?
Exactly
ah alright thank you


anybody?
i finished my economy system (first time using a db btw)

now i have to do a atm with buttons
That's nice ^^
yeah im loving dbs
guys dont spam this channel please
what lib is this?
discord_components
๐ช๐
Also, please use the correct code formatting ^^
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
discord components has horrible coding just saying
For just buttons, I recommend to use discord.py 2.0
yeah
Or directly switch to disnake or similar for future updates.
!d discord.ui.View and just subclass view
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
All right, but that's what I use. So the problem is, the nanny refers to facts when I press the button. I've rewrote custom id but then the buttons just didn't work
cant help with that sorry
I don't think having 2 same listeners but separated will work.
Pretty sure it will only take one of the two.
And discord_components is deprecated and archived, so it might lead to more errors.
So which one should I use? since I did this too much time I had to look for a well-functioning button system and my time is running out. I spend more with debug than I do with regular development because of the buttons.
You just need to replace all discord to disnake.
I have a couple questions.
1) How can I make it so the person who runs the command has to have one of three roles to run the command?
2) How can I make it so they can do `-add :angry_man:`, and they will get a role called `angry man`?
i can give you more info if you need it
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.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/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.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/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
use that decorator, passing it a list with the ID's of the 3 roles the command checks for
so like
@commands.has_any_role(roleList)
?
yes
kk, also should the role names or ids be in the list?
...
?
kk
?
use an arg and type hint it to a role obj
???
role: discord.Role
await member.add_roles(role)
how can I create a json that separates the command modules from the bot menu?
make sense
ik that part, i just dont know how to convert an emoji to text
what emoji?
i need a bit of (lang) context of this convo
i just joined
so you want a role set with an emoji?
like, make a role with an emoji?
lets say if someone says
-add ๐ฎโโ๏ธ
then they will get a role called @acoustic loom_man (SRRY FOR THAT PING, I DIDNT MEAN IT)
no like if he wants a role called happy he will use the happy emoji
one sec then
how can I create a json that separates the command modules from the bot menu?
wait for the emoji and remove the colons from it
how do i do that?
how can I create a json that separates the command modules from the bot menu?
?????????
str.strip()
!e
a = ":hello:"
print(a.strip(":"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hello
so, create a role called "Role_name ๐ฎ"
alr
its with custom emojis
so i cant do that
still works
py_strong is a custom emoji
you just get it in your server, then :emoji_name:
!e
a = ""
print(a.strip(":"))
@frank tartan :white_check_mark: Your eval job has completed with return code 0.
:HappyDog:
just remove all ints and :><
;-; how?
so, lets say i have an emoji, ":test:"
and i want to make a role, "role_name, :test:"
@frank tartan can you help me pls?
how...?
I want to separate the commands from the bot menu
??
how can I create a json that separates the command modules from the bot menu?
use str.split()
kk
and split it on a colon
how can I create a json that separates the command modules from the bot menu?
that is making no sense to me
you mean separete your bot file in cogs?
so, py @bot.command() async def create_role(ctx, role_name: str, emoji_id: int): emoji = await ctx.guild.fetch_emoji(emoji_id) await ctx.guild.create_role(name=f"{role_name} {emoji}") i think
How?
i dont want to create a role... i wanna give someone a role
you want to separate all commands in a separate file i suppose?
so just member.add_roles(role)
so like cogs?
how can i do it?
find a tutorial on yt about cogs
i dont use cogs so im not the right person to ask
cough cough
Uh
also, emoji name would be police_officer while the role name would be police officer
how do i make it so that when a certain person sends a message the discord bot replies immediately
I'm so confused on your question
more like
@bot.command()
async def set_role(ctx, emoji: discord.Emoji) -> None:
newemoji = str(emoji)
role = newemoji.split(":")
await ctx.author.add_roles(role)
Do you want to create a role, add a role, or get an emoji?
let me explain again. I want to make it so someone can do
-add ๐ฎโโ๏ธ
and they will get a role called police officer
๐งโโ๏ธ
an if statement
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
Would emojis be pre-defined
yes
wait
im dumb, roles would also be predefined...
You need to create a dict like
{'๐ฎโโ๏ธ': police_officer_role_id}```
Help me. What button directory should I use?
And other emoji-role_id pairs
cant you just make it a str and set the role
You mean library?
yeah
like i showed above
If you str the unicode emoji you get the unicode emoji don't you
Well personally I recommend disnake, but there are other options like pycord or nextcord, choice is up to you
not sure
No need
nvm that
just use the emoji name and set the role with it



