#discord-bots
1 messages · Page 721 of 1
await ctx.invoke(client.get_command(command))
!d discord.ext.commands.Bot.get_command
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/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 get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
im trynna make the ban command's "days" argument optional, and it has to be an int, the thing is if someone skips the day arg and goes to the member arg (str), it'll raise ```py
discord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "days".
async def ban(self, ctx, member: discord.Member, days=1, *, reason: str="No reason provided")
```
you cannot just skip it ...
you may like typehinting days with a union of int and str , and check if day is int or not
async def ban(self , ctx , member : discord.Member, days = Union[int , str], reason = "No reason"):
if isinstance(days , int ): # day in numbers was provided
else : # nah ```
Union here is typing.Union ^
and ill assume you are talking about the reason argument , not member , since its before the days arg
oh
class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.
When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.
For example, in the following code:
```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
``` An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
oh yeahh
im using the second method but ChannelNotFound keeps getting raised, the message id i used was in the context channel tho,
does this depend on cache or... because i just used a message id in channel a, and it doesnt work, i did it again and it worked, now when i use it in channel b, it doesnt work
Your code?
async def mock(self, ctx, message: discord.Message):
``````discord.ext.commands.errors.ChannelNotFound: Channel "None" not found.```
the rest of the stuff in the function are just embeds and ctx.send
But yeah, you must be getting/fetching the message?
Huh.....idk if that works, good luck then
it works when i use channelid-messageid, not when i do messageid
Huh, use, the context channel?
i dont want it to be limited to the context channel only
Hmm, well, you need the channel id the message wasnt sent in
await ctx.send(",".join([ctx.guild.get_role(role_id).mention for role_id in role_ids if len(ctx.guild.get_role(role_id).members) == 0])or "no"))
how can i place the ",".join(...) inside of an embed?
Just like a normal method
gotcha thanks
What can I say except you're welcome
lol
Ok im implementing a code similar to this but I want to turn off the first command. I only want commands with 2 words to work. What would be the best way to implement something like this
@client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
await ctx.send("Help! Categories : Moderation, Utils, Fun")
@help.command() #For this command (.help Moderation)
async def Moderation(ctx):
await ctx.send("Moderation commands : kick, ban, mute, unban")```
So i want to make a comand group but I want only the comands with 2 words like .help Moderation to work
I don't want .help to trigger anything
I will have sevral bots using something simialar but they will all have diffrent words that will trigger the command the problem is they all share the same first word wich will be convert
So that's why I dont want the first comand to work because using !convert would trigger all the bots at once.
Can I have a command group but have the first function with only one word not trigger anything?
would implementing something like this resolve the issue?
client.remove_command("help")
Does this even work
Or will this turn off all the comand groups that use the workd help
just pass in the help command...
its better to subclass the help command tho
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
What does this mean sorry
7.4. The pass statement
pass_stmt ::= "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
```py
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
Oh ok awesome
@client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
pass_stmt ::= "pass"
@help.command() #For this command (.help Moderation)
async def Moderation(ctx):
await ctx.send("Moderation commands : kick, ban, mute, unban")```
So would that be implemented like this?
Sorry I'm new to this
Or can i just use pass
@client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
pass
@help.command() #For this command (.help Moderation)
async def Moderation(ctx):
await ctx.send("Moderation commands : kick, ban, mute, unban")```
??
vote system?
yea sure , this works
subclass the help command, dont remove it
No it doesn't
No
reason?
how do i utilize args for slash cmds?
@Slash.slash(...
options=[
create_option(
name="continent",
description="Choose your continent.",
required=True,
option_type=3,
choices=[
create_choice(
name="North America",
value="hi"
), ...
could i then do smthing like
async def view(ctx: SlashContext, continent: str=None):
if value == "hi":
or, is there another way to use args
No
huh?
I have no idea why you even bother with that guy.
i thought they got something to say
lol ic
I was also waiting for an answer. Kinda wack to troll on a channel where people are looking for help
I appreciate your help. Thank you
No I'm ain't
erm why is it not running
pot the token dont write token
so need i to do wat
@commands.Cog.listener()
async def on_message(self, message: disnake.Message):
prefix = await self.database.find_one({'_id': message.guild.id})
if message.content == f'<@{self.bot.user.id}>' or message.content == f'<@{self.bot.user.id}>':
await message.reply(
f'Hey! My prefix for this server is `{prefix["prefix"]}`.',
mention_author=False
)
``` tryna make my bot to reply when it gets pinged, isnt working for some reason, no errors.
Put your actual token, a string, not TOKEN
go to discord developer portal
or message.content == f'<@!{self.bot.user.id}>':```
is that wrong?
its not wrong, pings can be <@{id}> or <@!{id}>
👍
give me command ideas
actual token = "my_token" ?
🤦♂️ bro did you copy code why'd you write token there
your meant to put your token in a variable, env, or as a string
ye
you copied it now x]
now remove that TOKEN from client.run
and add '<copy_paste_here>' as the string for client.run()
istg if you know how to make embeds you should probably know how to make the bot run
nvm i will change my token later
It gotta be a string
Remove the hashtag and replace it with 0x
?
do you know what a comment is?
anyone know how to make it so u can ping a specific role
wait ah
# is a comment, you gotta do 0x8ceb34
<@&id>
replace @client.commands() with @client.command()
done
now run your bot ig
import random
import discord.ext
client = discord.Client()
@client.event
async def on_ready():
print('hi {0.user}'.format(client))
@client.event
async def on_message(message):
username = str(message.author).split('#')[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'my_channel':
if user_message.lower() == 'hello':
await message.channel.send(f'hello mdfk {username}')
return
elif user_message.lower() == '!random':
response = f'ur random num: {random.randrange(100)}'
await message.channel.send(response)
return
elif user_message.lower() == 'random':
response = f'ur random num: {random.randrange(100)}'
await message.channel.send(response)
return
if message.content.startswith('$invite'):
await message.author.send('https://discord.com/oauth2/authorize?client_id=920313284920488017&permissions=534723950662&scope=bot')
return
@client.command()
async def embed(ctx):
embed = discord.Embed(title="how to make an discord embed", url="https://www.youtube.com/watch?v=UoROS78Vtr4", description="this is tutorial", color=0x8ceb34)
await ctx.send(embed=embed)
client.run("i will change my token later")```
@shadow wraith
bro why you have elif statement but using if after
You can’t make commands with discord.Client
^
that's why i asked, a uppercased C in a client means something is wrong, that's why i asked
erm so i need to do wat
Hello, I have a question.
Is there a way to disable the select(dropdown) of a message when the interaction timesout in discord.ui.Select using on_timeout?
(this question applies to discord.py 2.0, nextcord and pycord)
can anyone help me with my bot?
dm me i send u the source link
whats the problem?
yes
how?
super().__init__(Timeout={seconds})
yes, but on doing that, it just makes it so it will say "interaction failed", it dosent "disable" the dropdown
Wait ill look into my code
this is what i mean from "disabled" dropdown, timeout dosent do this
i use pycord, but dropdowns are same in both pycord and nextcord since both are a fork of discord.py 2.0
this remains same for all forks^
ok
Try: {className}.disabled = True
can someone help me? dm me
i send u the link(not free nitro :/)
Why in dms?
!d discord.ui.View.children , you need to use this kavoya , and .disabled=True
The list of children attached to this view.
i cant screenshot idk why
okay, thanks
window shift s not working
use snipping tool , or copy paste code
snipping tool not working
and the error is HUGEEEE
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
i mean
Do this
import discord
from discord.ext import commands
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
too long
LOL
local variable 'emote' defined in enclosing scope on line 8 referenced before assignment
it shouldnt be error
=.=
is emote a folder ,or a python file?
and emote is some function / class inside it?
can you put it in github so we can see it
emote.py is built for async def emote():
just open the link it has the code...
just press on the link :/
understandable , try chaning the function name to something else
local variable 'emote' defined in enclosing scope on line 8 referenced before assignment
is the error yoy get right?
my_emojis probably
ok
or anything u want
my_emote can right?
yea ig
still the same
local variable 'my_emote' defined in enclosing scope on line 8 referenced before assignment
show the function
here
i just changed the name
thats not how global variables work
thank you bot, very helpful
this is my code:
@bot.command(aliases=["8ball"])
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def eightball(ctx, *, question):
async with aiohttp.ClientSession as session:
request = await session.get("https://8ball.delegator.com/magic/JSON/e")
request1 = await request.json()
randomAnswer = random.choice(request1.get("magic").get("answer"))
embed = disnake.Embed(
title=question + "?",
description=randomAnswer + ".",
color=disnake.Colour.random(),
)
await ctx.send(embed=embed) # gentle 8ball command.
anyone wonder why this aenter issue is coming?
that error usually raises with context managers
!d aiohttp.ClientSession
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
i eventually figured that out
Nice
but now apparently the embed is sent super slow, and like, the answer which is showing is blank or just u
Is it possible to use 1 @bot.command() code block and have multiple names and respective command_alias with the same block
you mean a command with lots of aliases?
No.
Multiple commands names
Like i want to use the same code block but different names.
name="barrows1", command_alias=["barrow1","bro1"],
name="barrows2", command_alias=["barrow2","bro2"],
name="barrows3", command_alias=["barrow3","bro3"]
)```
something like this?
ok
how do I use aiohttp and send data to a site and then the send the output of the site in the discord bot's output?
Example
thanks bhai
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/dopubisifi.py
⏫ my_emote.py
local variable 'my_emote' defined in enclosing scope on line 8 referenced before assignment
help
I can't find the error here
@bot.command(aliases=['clean', 'purge'])
async def clear(ctx, n=0):
if n <= 0:
await ctx.send("Please add the amount of messages to delete")
else:
await ctx.channel.purge(limit=int(n))
cembed = discord.Embed(title='Done!')
cembed.add_field(name='Deleted Messages:', value=f'{n}', inline=False)
cembed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
cembed.timestamp = datetime.datetime.utcnow()
await ctx.send(embed=cembed)
Mind telling the error?
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Does View raise any exceptions on timeout?
I mean like how to handle timeout outside of on_timeout
how do i make it so it can be multiple channels that get the welcome messages
etc for multiple servers
Store welcome channels ids somewhere and access them
to make OAuth2 url, does it need to be authorised?
I mean, it seems like I can't use local host http://127.0.0.1:5001/
looking for someone with same name as u
Oh
https://paste.pythondiscord.com/kuhicimaco.py
⏫ main.py
https://paste.pythondiscord.com/dopubisifi.py
⏫ my_emote.py
local variable 'my_emote' defined in enclosing scope on line 8 referenced before assignment
help
line 593 main.py
What are people using to build a discord bot in python now that discord.py is archived?
how to solve this?
wdym
what is archived
2021-12-31T10:51:47.234622+00:00 app[worker.1]: discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
u use the 24/7 monitor thing in replit?
try not to leave an error before letting it run itself for few hours
cuz it will restart non stop for that time
and thats how u get rate limited i guess
i use heroku
can u help me?
well, read the discord developer documentation, you can see which requests make what action and such.
i doesnt mean this one
How can I fix that???
The url needs to be inside a string.
With this? '
@slate swan
the library discord.py has been archived aint it, due to the person maintaining it not liking the direction discord is going with slash commands https://gist.github.com/Rapptz/4a2f62751b9600a31a0d3c78100287f1 so wondering what other library would be worth looking into
A single quote.
Not this
Both ' and " are strings.
url="https://..."
Ty
do you know so that nothing like that happens again?
why isnt this working ;-;
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f"cogs.{filename[:-3]}")
well, don't send messages or start and close the bot too much
in the cogs.add class was the class name class Add(commands.Cog) or similar?
nope wait
class Add_data(commands.Cog):
def __init__(self, client):
self.client = client
def setup(client):
client.add_cog(Add_data(client))
and my filename is add.py
Who are "we"?
Send me a friend request.
@slate swan client dosnt have cogs
how can i add a code block in a field?
!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.
can someone explain where did this come from?
anyways why can't others react, only the author of the command can react and change it, how can i make it so anyone can react?
@bot.command()
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def rhyme(ctx, *, word):
try:
def check(r: disnake.Reaction, u: Union[disnake.Member, disnake.User]):
return u.id == ctx.author.id and r.message.channel.id == ctx.channel.id
async with aiohttp.ClientSession() as session:
newword = quote_plus(word)
Api = await session.get(f"https://api.datamuse.com/words?rel_rhy={newword}")
API = await Api.json()
randomWord = random.choice(API).get("word")
__what_rhymes__ = await ctx.reply(
f"Word: {word}\nWhat rhymes: {randomWord}"
)
await __what_rhymes__.add_reaction("🔄")
while 1:
try:
event = await bot.wait_for(
"reaction_add", check=check, timeout=30.0
)
except asyncio.TimeoutError:
break
except IndexError:
await ctx.reply("No more rhyming words can be found. :(")
else:
newWord = random.choice(API).get("word")
if str(event[0].emoji) == "🔄" and not event[1].bot:
await __what_rhymes__.edit(
content=f"Word: {word}\nWhat rhymes: {newWord}"
)
else:
pass
except IndexError as ie:
await ctx.reply(f"There are no words rhyming with {word} :(")
you hovered over a module
what?
you hovered over a module's name
that's the place where the error comes from
i don't see the error
Will I get banned if I try to change role colors every 10 mins? (ping me)
wait i see it now
¯_(ツ)_/¯
I don't think I will tho
huh, wdym
its probably just an import error, restart your code/text editor
how do i check if a file is uploaded to a command use for exaxmple uploading an image and having the text above it be like >rotate <degrees>, i know how to rotate the img just wondering how i can get the image
@commands.command(aliases=['av'])
async def avatar(self,ctx, member: discord.Member = None):
if member == None:
member = ctx.author
embed = discord.Embed(title=f"Avatar for {member.name}",description=f"**Link as**\n[png]({member.avatar.url.as(format='png', size=1024)}) | [jpg]({member.avatar.url.as(format='jpg', size=1024)}) | [webp]({member.avatar.url.as(format='webp', size=1024)})", colour=discord.Color.blurple())
embed.set_image(url=member.avatar.url)
await ctx.send(embed=embed)
No error? But the bot don't send the embed?
use member or ctx.author and also whats Blurple ?
discord color?
There is something rong with this
member.avatar_url_as
member.avatar.url.as
are you using discord.py 2.00 or 1.7 ?
2.00
look in the docs about formatting tbh, i've got no clue
salut
s'il vous plait qui maîtrise le langage Golang ici ??
hi here
please who is fluent in golang language here ??
member.avatar.with_format iirc
hey i am making something related to leveling and i have this in a cog
else:
xp = stats["xp"] + random.randint(30, 50)
collection_name.update_one(
{"id": message.author.id}, {"$set": {"xp": xp}})
lvl = math.floor(0.1 * math.sqrt(xp))
nlvl = lvl + 1
xpnxtlevl = (100 * nlvl * nlvl) - (100 * lvl * lvl)
if (xp - (100 * lvl * lvl)) >= xpnxtlevl:
embed = discord.Embed(title="🏆 LEVEL UP! 🎉",
description=f"Congratulations **{message.author}**!\nYou've leveled up to level **{nlvl}** 🎉",
color=discord.Color.red())
```but when i level up it doesnt send the message
how do you send a file
in discord bot
because i have this image manipulator command which uses PIL for it but i got stuck on how to send a file, this is my code:
@bot.command()
@commands.guild_only()
@commands.cooldown(1, 3, BucketType.default)
async def rotate(
ctx: commands.Context, degrees: int = 90, image: disnake.File = "amongus"
):
os.chdir("/Users/sadancooler/Documents/Code/Python/bots/infinity/images/")
with open(f"{image}.png", "w"):
if image == "amongus":
__image__ = Image.open("amongus.png")
__image__.convert(degrees).save("amongus.png")
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
i just cut it while pasting it i am sending it
How to copy ID of the animated emoji in discord? If i don't have discord nitro kekw
On desktop:
- Open emojis tab
- Press cntrl + shift + i
- Press select element (the thing in the upper left corner)
- Click the emoji you want using the select element
- It will redirect you to a html code
- Right click and select edit HTML
- you will see the id there
Is there anyone who have made a discord bot that accept usdt or trx as crypto ???
Can you tell me how you do it ???
Thanks!
But it don't trigger my animated emoji, if i use it with <merry4:924255066649669652> in my code
merry4 is the name of emoji
after : - ID of the emoji
Ye
Try getting the emoji with the ID
Also
<"emoji_name": emoji_id>
What does this show?
Ah guessed so
hmm maybe try putting the id in quotes too
Dunno if that matters but try it
Ah nice
I forgot a before emoji name
oh
solution - <a : merry4:924255066649669652>
Ah ye
without spaces after a and before merry4
Hello
I keep running into a few errors with my code
It's for a levelling bot
lemme get the code real quick
Here are the errors:
it's urllib i think
Yeah
read as url-lib
yeah
but that also brings up some errors
Also, I dont understand why it brings up an error for import levelsys
also, I haven't used the word 'lifetime' anywhere
hey, im trying to find the guild object from an ID in a cog. I wrote this but self.adminGuild = None
def __init__(self, client: commands.Bot):
self.client = client
self.adsSent = 0
self.embedInd = 0
self.embeds = [self.get_adEmbed(), self.get_servEmbed()]
self.adminGuild = self.client.get_guild(int(925459999856136263))
print(self.adminGuild)
self.errorChan = self.adminGuild.get_channel(int(926482390132596736))
self.adsLogChan = self.adminGuild.get_channel(int(926483060411756614))
does anyone know what Im doing wrong?
ah i worked it out!
the bot needs to be ready so the server is in the cache or something i think
so i moved that to a on_ready event
is that the best way to fix it?
imo using an rpi is the best
hello im making a commadnd for rps (rock paper scissors) game and want to use discord.ui.button this is what i have but not sure how to get exactly what button label/ choice of rock paper scissors they chose . How do you do this?
pls help im stressed
What is the best solution to having as close a blank name field in an embed?
\u200b
i think its that character if not just search blank character code or smth
I'm going to try it 🙂
The other ones I have tried so far haven't worked just yet
Awesome! That worked, thanks Krafty
Is there a way to make an embed message use more horizontal space?
ur embed looks something like this right?
embed.add_field(name="something", value="content") right?
so they are all name elements right
I want it to look cleaner/more uniform
No they are values
the name value is the alt code you gave above
i dont actually know that much about embeds but a dumb way to do this would probably be try using diferent amounts of spaces
if that doesnt work then use name instaead of value
that isn't a possible solution since the words change
oh right
I'll try using name instead of value
yea cos my help command for my bot is relatively well aligned without uing spacs and that
hmmm
idk really the problem is just with the "visit" part tbh
im sorry i couldnt help on that one :(
Is there a header field?
or similar? If so perhaps it could push the words down and maybe they would align better
add values to the fields, maybe they'll align themselves,don't worry just yet
I have values as \u200b character
no, the three arguments aare just name, value, and inline
u can have a look at discord.Embed in docs
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
is there a way to set the default invite url for the bot (so i can always access it)
If I want to do something like image or set_image what is the syntax to use them?
embed.set_image i think
and what about calling it? It has two separate methods
^
wdym calling it
just set_image then await ctx.send(embed=embed)
embed being ur discord.Embed thing name
i gtg now srry i couldnt help tht much
how do i get the clicker of the button
!d discord.Interaction.user
The user or member that sent the interaction.
there we go
Hmm this is odd -
self.client.embed_widener = 'https://cdn.discordapp.com/attachments/544302254694465547/926497254611759135/unknown.png'
embed.set_image(self.client.embed_widener)
set_image method takes one arg, url, but when I try to run the code as above I get:
Embed.set_image() takes 1 positional argument but 2 were given
so discord.Interaction.author is the one that like uhh
@heavy folio what's the difference between discord.Interaction.author and discord.Interaction.user
The user or member that sent the interaction.
so how would i implement a check if the author is not the author x] like for example the guy clicking the button when the command author is meant to
hmm idk if this is the best way but i pass ctx as an argument in init, then ```py
if self.ctx.author.id != interaction.user.id:
# do stuff
ok but how pass ctx as an argument. self.ctx = commands.Context?
instance of ctx, not the class object
figure it out, pass ctx as an arg in __init__ and self.ctx = <instance of ctx>
is it possible to do an in line if statement for the values of a tuple?
here's my attempt lol
('Burst Count:', server.burst_count if server.cypher_mode == 'burst' else 'Word Count:', server.word_count)
Nope
Encode what?
Does anyone know what code is needed for my bot to assign posts by reaction?
roles* and you can use the on_reaction_add or on_raw_reaction_add events
!d discord.on_reaction_add
nvm
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
How do I get the list of commands available to my discord.py?
What version are you using? You can check the docs
@bot.event
async def on_reaction_add(reaction, user, ):
guild = ctx.guild
postrole = discord.utils.get(guild.roles, id=925783050984505385)
if reaction.emoji == ":unlock:":
await on_reaction_add(user, postrole)
its not working
can you type it into this code pls
why to
use the add_role method
on the user parameter
why
await ctx.send(str(bot.http.__session.headers))
AttributeError: 'HTTPClient' object has no attribute '__session'```
it was Bot.commands
But what's the problem with my code
what are the best alternatives to discord.py rn
on_reaction_add is not a method, its an event
disnake, nextcord, pycord
most people use disnake so...
Why not use Guild.get_role?
that can return None too, same thing
My problem is to put this in the code so it works
hey! iv hosted my bot with heroku and github. In the bot, different json files are edited. How does this work? it doesnt change the github repo so does it just change it temporarily until its redeployed?
That's why I needed someone to teach me how to put this in the code
Do you know to make my code work?
.
Does anyone know what code is needed for my bot to assign posts by reaction?
this is my problem
and I dont know how to fix it
code wont always solve the problem, your understanding of the working of things matters the most
yee good
In everything I've programmed, I realized at the end, after being helped to understand, I'm not experienced but I'm not new either.
I just want to know whats wrong with my code
on_reaction_add is not a defined method
you use the add_roles method for that
!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.
ok I will try it one sec
but I just want to give the role if someone reacts to the message
.
@glacial kernel
.
https://cdn.discordapp.com/attachments/926173376379248652/926523451043377162/1B147043-1034-4904-814D-E85BCE552226.jpg this happened to one of my friends on replit, he just made his first bot and tried to test commands but instantly got blocked from API and got this for some reason
rate limited
replit shows all the html content
Replit is no good for hosting
dude didn’t even run a single command lol
replit it is
It’s not a dpy issue, it’s a replit issue
I see
Here’s from official dpy server
yeah, it'll be fixed itself in a few hours
@bot.event
async def on_reaction_add(reaction, user):
guild = ctx.guild
postrole = discord.utils.get(guild.roles, id=925783050984505385)
if reaction.emoji == ":unlock:":
await add_roles(postrole, reason=None, atomic=True)
It says ctx is not defined
Add ctx into the parameters
ok
reaction.guild*, and user.add_roles
my love, thats an event
@bot.event
async def on_reaction_add(reaction, user, ctx):
guild = reaction.guild
postrole = discord.utils.get(guild.roles, id=925783050984505385)
if reaction.emoji == "🔓":
await user.add_roles(postrole, reason=None, atomic=True)
It says on_reaction_add() missing 1 required positional argument: 'ctx'
ale ze ashley
ctx isnt a parameter
There are only reaction and user params
@bot.event
async def on_reaction_add(reaction, user):
guild = reaction.guild
postrole = discord.utils.get(guild.roles, id=925783050984505385)
if reaction.emoji == "🔓":
await user.add_roles(postrole, reason=None, atomic=True)
like this?
Yups
is there a has role attribute for slash cmds?
Do u mean a check?
yeah
U can do if <role> in interaction.author.roles replacing the role with the actual role object
alright, thanks
Or u can also use utils.get, but that's sometimes slow
Now it says this: 'Reaction' object has no attribute 'guild'
yeah, i prefer this
reaction.message.guild
where do i put this
Sure it's a bit.... better to see also, but it's slow, so, uhhh
Replace with reaction.guild
ok
I did it bro thank you so much
(:
by now you know what command is needed to alert the outputs
???
on_member_join
this is the command to alert when someone enters which command to alert when someone exits
!d discord.on_member_remove
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
thank you
(:
how do i make a slash command where the argument is a role?
i know how to make a slash command, i just dont know how to create role choices under an option
how can i fix xD
my code:
@client.event
async def on_member_join(member):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
for channel in member.guild.channels:
welcome_dict(member.channel.guild.id)
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
await channel.send(embed=embed)
@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict[str(ctx.guild.id)] = str(channel.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')
@client.event
async def on_guild_remove(guild):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict.pop(guild.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
my error:
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\wedaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\wedaa\Desktop\discordbot\me code.py", line 62, in on_member_join
for channel in member.guild.channel:
AttributeError: 'Guild' object has no attribute 'channel'
u didnt save the file before running
i did save
well your error says you have py for channel in member.guild.channel: but u actually have py for channel in member.guild.channels: in the code
i just save the file and it is the same
Did you restart the bot?
Does anyone know how to get the bot to mention the mentioned user
Like ctx.author.mention but for the mentioned user
yeah
Is there a way to get an image attached to a slash command?
Would like
image: disnake.Attachment```
typehint work
idk how slash commands work
can you get a message object from it?
you probably can
image = message_object.attachments[0]
damn everybody went to celebrate the new year
Depends which package you are using.
In diskane, after you sent the message in response to a command, you can use ApplicationCommandInteraction.original_message to get that message object, usefull if you want to edit it or delete it
This will take the first response you sent to a command trough Application, which means that this will not work for other message you could send
How to get VoiceClient from guild? I only get VoiceProtocol but that's not what I need I think
!d discord.Guild.voice_client
property voice_client: Optional[VoiceProtocol]```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
oh
Yeah
what do you need it for?
For is_playing
music bot?
Kind of

So how to get that stupid voice client
I can only think of ctx
The only way I see is to create a variable and place the state on connection to there
!d discord.ext.commands.Context.voice_client
you need the full path
property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
Still protocol
Yes
Create a variable in cog and then do everything to it, I will see if it's possible
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
does anyone know why this won't add the color?
self.add_item(discord.ui.Button(label='Invite Me', style=discord.ButtonStyle.green, url=url))
seems good
That's the only way we can get the VoiceClient from it turns out
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
If url is provided it automatically sets the style to discord.ButtonStyle.url and you can't change it
ahh okay thanks
How do i accept a role as a slash command argument and then assign that role to the user who invoked the command
What's the proper way to catch CommandNotFound error?
!d disnake.disnake.ext.commands.on_command_error
disnake.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Bot.on_command_error "disnake.ext.commands.Bot.on_command_error")).
So I just overwrite that method within a class inheriting client and it will work?
Why do I keep seeing disnake?
is this a new version or something?
@commands.command()
async def daily(self, ctx):
async with self.db.execute(
f"SELECT time from 'economycooldown' where guild_id = {ctx.guild.id} and user_id = {ctx.author.id} and type = {str('daily')}",
) as cursor:
coolDownTime = await cursor.fetchone()``` why does the bot return this error? https://cdn.discordapp.com/attachments/784465822180704340/926553300122370068/unknown.png
the error is pretty-much self explainatory
ik but
did you restart/save your bot?
yea
your code seems correct though
yea ik
yeah , daily is a row

thats why i dont know whats wrong
ill guess its because of f strings...
hm
How do I listen for a CommandNotFound error in a cog? What decorator do I use?
damnit
help xD
my error
File "c:\Users\wedaa\Desktop\discordbot\bot.py", line 53, in on_member_join
for channel in member.guild.channel:
AttributeError: 'Guild' object has no attribute 'channel'
my code:
@client.event
async def on_member_join(member):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
for channel in member.guild.channel:
welcome_dict(member.channel.guild.id)
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
await channel.send(embed=embed)
@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict[str(ctx.guild.id)] = str(channel.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')
@client.event
async def on_guild_remove(guild):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict.pop(guild.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
execute(
"""
SELECT time FROM economycooldown
WHERE guild_id = ? and user_id = ? and type = daily
""" ,
(ctx.guild.id , ctx.author.id)
)```
what
use on_command_error event and compare the error arg with CommandNotFound
you don't do that in a cog
I want to have an error handling cog if possible for neatness/cleanliness of code
its possible in any file you want , just in case of cogs you'd be using an listener
What decorator do I use to establish a listener?
@Cog.listener()
if imported
indeed
what args do I pass into the decorator if any?
says the type is str name
name of what I don't know
channels*
its optional , you can either pass the event name in it , or name the function ```py
@Cog.listener('on_command_error')
async def call_it_whatever(self , ctx , error):
....
@Cog.listener()
async def on_command_error(self , ctx , error):```
none

now i get dis: File "c:\Users\wedaa\Desktop\discordbot\main.py", line 54, in on_member_join
welcome_dict(member.channel.guild.id)
AttributeError: 'Member' object has no attribute 'channel'
a member doesn't have a channel
its member.guild? whats member.channel supposed to mean
I had this for testing -
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
print('we hit this')
if isinstance(error, discord.ext.commands.CommandNotFound):
print('yeah we got one!')
print statements to see if it even enters the blocks, it doesn't even print 'we hit this' which should print if every it enters the block
is the cog loaded?
Is the function inside the cog?
and yea , what kayle said
that was it haha, I had just added the cog, it works 🙂
oof
ok
I set it up but didn't list it in main to load the cog
now it works and hit both print statements 🙂
Ah, I just saw that in the traceback so I went with it since it couldn't be wrong haha
just... why
What is the deal with disnake? I have been seeing it everywhere, am I completely oblivious and have been using an old version until now?
🏃♂️ because im anyways not using anything other than these
Usually I do from disnake.ext.commands import *
I'm still using discord.py lmao
its one of the sexiest forks or discord
ooh
*of
nice, what do I need to know about converting my project into disnakke?
which is regularly updated and maintained
nothing , its just discord.py v2.x continued
How involved is updating to be compatible from latest dpy?
ooh, so I just change all my imports to disnake and it should work out of the box?
yes
ooh cool, I will have to do that then
it's the same
thank you 🙂
the only difference is that it's still developed
meaning new things will get into disnake but not dpy
or you can pip install disnake[discord] to install disnake as discord :p

haha ooh, that's smart
and it won't have any conflicts overwriting if I do it that way? Or should I first uninstall dpy to be safe?
it will override discord.py iirc
@commands.command()
async def tmp(self, ctx, role: discord.Role):
for m in ctx.author.guild.members:
temp = False
for role in ctx.author.roles:
if role.id == 898641586622197801:
temp = True
if not temp:
try:
await m.add_roles(role)
print("success")
except Exception as e:
print(e)
await asyncio.sleep(5)
I have an administrator role on the bot and it is higher than the role i am specifying and yet every single member results in a permissions error. It doesn't make any sense...
Thank you 🙂
hello, i need to do a database (.json) thtat save guilds id, can someone help me ?
json no database
.-., i need to do a file that save guilds id to do a variable per guild
I recommend a database 
Json is not a database
Use an actual database
I recommend psql
yes
PostgreSQL
best one
Indeed
datetime.now()-inter.created_at```
Gives error
```py
TypeError: can't subtract offset-naive and offset-aware datetimes```
How to substract them
I don’t develop bot that much nowadays, btw is the project ongoing?
Yes
We got Caeden
And most developers
Wait I shouldn’t be inviting I wasn’t tasked with that 
Ik
this the bot with 240 commands?
we got 21 devs so far
No
*35 but some of them are moral support
wt
there are only 21 working on the bot i thought?
that's a lot
I can't imagine
currently coding an AI algorithm
Currently being useless in web development 💀
how everyone would understand every shit 20 other people wrote
But I’m working on the ide 💀
i thought caeden was developing the ide?
we are getting off topic for this channel, perhaps we talk about this in the actual server and steer this channel back to topic.
yeah but it is discord bots
its for aspects regarding discord.py development.
A bit late, but check to make sure you have member intents enabled in the dev portal
no
discord.py is one of the sub-subjects
main subject is discord bot development
hey, i have a question on how member.created_at.timestamp() is measured in, does it count how many seconds ago a account was created? Dumb question as ive proven it wrong but i may be crazy. Is the a way to see say how many hours ago an account was created?

Unix time (also known as Epoch time, Posix time, seconds since the Epoch, or UNIX Epoch time) is a system for describing a point in time. It is the number of seconds that have elapsed since the Unix epoch, excluding leap seconds. The Unix epoch is 00:00:00 UTC on 1 January 1970 (an arbitrary date). Unix time is nonlinear with a leap second havin...
It's the number of seconds since 00:00:00 UTC Thursday, 1 January 1970
oh ok
I believe that created_at is a datetime object, so you should be able to subtract that from a now() object, and get the number of hours
topic literally says:
relating to Discord bot development with discord.py
with what library
any python
👍
:thumbsup_tone5:
🤔

ctx.author.metion does it still work?
need help with showing latency
i have the message.content.startswith instead of ctx.send
How do I handle command on cooldown in a cog?
I was looking at docs but wasn't entirely clear on it, I assume it will be a listener but what method do I use? command_on_cooldown?
message.content.startswith is not equivalent or serving the same purpose as ctx.send
import discord
client = discord.client()
@client.event
async def on_ready():
print('online and logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'quit':
await message.channel.send('hello {ctx.author.mention})```
File "main.py", line 11
@client.event
^
IndentationError: unindent does not match any outer indentation level
Nevermind figured it out above 🙂
i think im blind
use code blocks
i cant find error
it is horrible looking at code like that
`
!resources @slate swan
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
return is going to break out of your code
so it won't read anything after the break
return is something that goes on the end of functions
I assumed the indentation was intentional
it's not
as the conditionals have two different intents
even the error is about indentation
I didn't even see the error :p
.

and idk how client works
discord.Client() should it be
with a capital C
o
help
my error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\wedaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\wedaa\Desktop\discordbot\main.py", line 54, in on_member_join
welcome_dict(member.channel.guild.id)
AttributeError: 'Member' object has no attribute 'channel
my code:
@client.event
async def on_member_join(member):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
for channel in member.guild.channels:
welcome_dict(member.channel.guild.id)
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
await channel.send(embed=embed)
@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict[str(ctx.guild.id)] = str(channel.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')
@client.event
async def on_guild_remove(guild):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict.pop(guild.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
still?
you've been answered
.
i dint see that xD
np
ty
help
my error
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\wedaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\wedaa\Desktop\discordbot\main.py", line 54, in on_member_join
welcome_dict(member.channel.guild.id)
AttributeError: 'Member' object has no attribute 'channel
my code:
@client.event
async def on_member_join(member):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
for channel in member.guild.channels:
welcome_dict(member.channel.guild.id)
embed = discord.Embed(color=0x4a3d9a)
embed.add_field(name="Welcome", value=f"{member.name} has joined {member.guild.name}", inline=False)
embed.set_image(url="https://media.giphy.com/media/f4V2mqvv0wT9m/giphy.gif")
await channel.send(embed=embed)
@client.command(name='setwelcomechannel')
async def setwelcomechannel(ctx, channel: discord.TextChannel):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict[str(ctx.guild.id)] = str(channel.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
await ctx.send(f'Sent welcome channel for {ctx.message.guild.name} to {channel.name}')
@client.event
async def on_guild_remove(guild):
with open('welcome.json', 'r', encoding='utf-8') as f:
welcome_dict = json.load(f)
welcome_dict.pop(guild.id)
with open('welcome.json', 'w', encoding='utf-8') as f:
json.dump(welcome_dict, f, indent=4, ensure_ascii=False)
how can i make system that can add points to users checks theirs points and rank promotes can promote sameone to highter rank or domote to lower rank i mean when samone reach like 100/100 points admin or some of staff members can promote sameone or when they dont get point the staff members can demote by using command
and the adding points by usuing command like +addpt @nick number of points
?
pls
discord.Member.channel isnt a thing
you also didnt close the string on discord.Embed.set_image()
bro this is the exact same code as before

you copied the whole thing and came back to the same place with the same error
outstanding move
?
Where do u store points?
You just need to have a db set up, from there It’ s basically just simple crud operations
why did you copy my code
straight up
xD
the AUDACITY
😂
don't think u should worry
the guy probably doesn't know how to even set up your json file
oh yeah xD
the id should be what you need
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
if you're using 2.0 you can use this instead to check if the member has a role:
!d discord.Member.get_role
get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.
New in version 2.0.
what is this? what am i looking at?
firsty i dont make a code
all arguments before / in a function definition indicate that they are positional only
i.e. they can't be passed like role_id=1
i mean made i mean started making
cuz im asking how can i make it and how should the code look like or something
is this disnake?
yes
!d disnake.Client.getch_user
await getch_user(user_id, *, strict=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Tries to get the user from the cache. If fails, it tries to fetch the user from the API.
oh

how about disnake.Client.fet(user_id)? (first fetch, then get)
no, FIRST fetch, then get
getch seems like the lazier way
and why tf can't you fetch a role? you can only get it
probably cuz get will always succeed
stay away from API calls whenever it's possible
why are you using the main class
and indeed, a member doesn't have get_role
discord.Member is the main class
if not(role in cache):
print("you're screwed")```
it will be

tho this isn't python syntax wtf
discord.Member
replace that
get role from guild
discord.utils.get(ctx.guild.roles, id=(role_id))```
try this way
how can i make system that can add points to users checks theirs points and rank promotes can promote sameone to highter rank or domote to lower rank i mean when samone reach like 100/100 points admin or some of staff members can promote sameone or when they dont get point the staff members can demote by using command
and the adding points by usuing command like +addpt @nick number of points how the would like etc
use a database
make database calls all the time
nothing
it's okay without brackets
you are obsessed with brackets

yes
nothing
id=role_id```do the same thing
no
!d discord.ext.commands.Bot.load_extension no, that wont work
load_extension(name, *, package=None)```
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`.
you can have a list, then iterate through it and load the extensions
EXTENSIONS = ['cogs.xxx', 'cogs.yyy', 'cogs,zzz']
mhm
Hi, I upgraded to 2.0 and now my button event isn't working.
.help
Many people prefer to have it dynamic, looping through every file in a certain folder and adding it as an extension
That way when you add a new extension, you don't have to also add it's name in the list, you just need to make the extension and it automatically loads it for you
Nah just in your main bot file
It should be one of the first thing the bot does
what isnt working?
There is no "button event"
There are interactions, but those are for other things as well such as slash commands and select menus
Before I had this:
@bot.event
async def on_button_click(interaction):
if interaction.component.label.startswith("test"):```
And it worked, but as soon as I installed 2.0 it doesn't seem to work anymore
!d discord.on_interaction is what u looking for @silent portal
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/master/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
why are you using on_interaction tho..

Store your cogs in a folder and loop through the folder loading the cogs
No hardcoding needed
!d os.listdir
os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.
*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.
This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.
Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
hey why when i put one more id the channel whitelist dont work
bot.command() # Stock command
async def stock(ctx):
if ctx.channel.id == 926669256270176346 or 926669246128349195:
Try to loop like
!orgotcha
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
if ctx.channel.id in Ch
"feeling"
what error?
Aiphttp upgraded to new version so old version of discord. Py not working
this is a third party lib event.
yep, discord.py needs aiohttp 3.6 - 3.8
2022 is ?
So just install the required version?.... ( Wrong reply)
So just install the required version?....
Lol
2022 is bruh
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
how can i make system that can add points to users checks theirs points and rank promotes can promote sameone to highter rank or domote to lower rank i mean when samone reach like 100/100 points admin or some of staff members can promote sameone or when they dont get point the staff members can demote by using command
and the adding points by usuing command like +addpt @nick number of points
? i only need how to make this system cuz me dont know how to make this system
Use a database to store information, and make certain commands to fulfil your needs
but i dont know how to make exacly this command bursh
what are some reasons for your bot to get rate limited?
too many requests
Using replit
o im using repl lol
or that
how do i fix it? and how long will i be blocked from makig requests for
1 hour usually, or less
Raspberry pi
An old laptop
Pay for a VPS
me dont know but i know where u can host your bot
Don't say Heroku
not heroku
ok ill try some alternatives later
u can use danbot host
how often will this happen?
its free hosting
ok ill use that for hosting
ok
and in the dan bot hosting u can write in python too so u dont need to upload x timex the same file of bot with more futures to bot
Dan bot hosting is bad. I know a few people whose token got leaked with them
heh
How does that even happen. The host leaking tokens?
i dont think so
Are you sure this wasn't down to the client's negligence?
cuz people use this hosting and their bot tokens dosent got leaked
is there a way to get the thread's parent channel
so i have a list of dictionaries, like:
cases = [{'Case Number': 1, 'Date': date}, {'Case Number': 2, 'Date': date}]
I want to iterate through it, and add fields to an embed, so that it looks something like this:
Case Number 1
Date: date
Case Number 2
Date: date```
any idea how i can do this?
hmm
what i'd do is ```py
for i in range(len(cases)):
then do stuff, the name of the embed can be something like ```py
f"Case Number {i}"
not sure if that works tho
thanks, i'll try that
ok
Proceeds to get
Case Number: {'Case Number': 1}
