#discord-bots
1 messages · Page 1150 of 1
nope, you cannot do that message.content there. bumpreminder is the name of command there
okay
It didnt work
hi guys i have a problem: /home/container/bot.py:718: RuntimeWarning: coroutine 'sleep' was never awaited
asyncio.sleep(10)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
my code
async def bumpremindme(ctx):
await ctx.send("ok")
asyncio.sleep(10)
channel = bot.get_channel(992511703155740712)
await channel.send(f'{ctx.author.mention}bump again 🤢')```
Hey ash 👋
took me 10 seconds to determine the right spellings for asyncio
ok
thanks
👋

how can i add description to slash command parameters description?
Bro what the
which lib?
print([channel.name for channel in ctx.guild.channels])
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command()
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
I have no idea how to get these things
you cant get them, you make them
hi zeffo
Hello
I have no idea
Hmm not related to active channel tho
channel = bot.get_channel(989514935459540992)
is there a way to use channel names instead of id's
i use command tree
It's related to that only
@tree.command(guild=discord.Object(id=guild_id), name="roll", description="Rolling Dice")
async def roll(interaction: discord.Interaction, dice:app_commands.Range[int, 1, None]=10):
await interaction.response.send_message(f"{random.randint(1, dice)}")
its better to use id but you can use discord.utils.get to get it using the name
Hard
Shouldn't matter
tree dont have describe method
Alr I'll make one
I just realised that when guild ids get into the mysql get changed into a wrong number
@client.command()
async def insertTables(ctx):
for guildid in client.guilds:
print("befor inserting")
servid = guildid.id
print(servid)
#here in console it prints id correctly
await ctx.send(servid)
#in discord send id and they are unique and correct
cur.execute(f"INSERT INTO Servers(serverid,sub,subdate) VALUES({servid},0,CURDATE());")
#get changed and saved into db
conn.commit()
print("done") ```
anyone knows what is happening i dont event encrypt it and i dont why is it changing in db
I know, the app_commands.describe decorator should work
oof global
yes it works thank u , i love u
No that's bad for me
I would not be able to learn
how do we create threads using discord.py?
I mean I take that as a challange
!d discord.Message.create_thread
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a public thread from this message.
You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.
The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel").
New in version 2.0.
has it been resolved?
how??
you can just call bot.get_channel in the list comp
why do you have a list in the first place, which channel do you want to get?
That iteration makes no sense, you have a list of channel objects which you are using to get a list of IDs of channel objects, and then convert it to a list of channel objects again????
If you want a specific channel use get_channel or ulilts.get straight
can i add subcommand to @tree.command
There's a class called command group or something in dpy for slash group commands
Hello, I currently got an issue :
After someone submit a modal, I want to send a DM to an user from his ID, so I need to retrieve it with client.get_user
My issue is, by doing this I'm getting error due to circular import (client trying to load cogs, cogs are using custom buttons that load my modal, which needs client..)
I guess I'm doing something wrong how can I handle this? Thanks for any help 🙂
You can pass the client object in modal's init or set it as an attribute of the modal
your client (or bot) object can be retrieved from discord.Interaction.client from on_submit function
Ofcourse
is there any example
Check the channel pins, I think there's an example in the gist
Damn, I missed this I'm dumb xD
thanks
Uwu group 💀
lol
yes i saw it but i want to implement it to tree
bu i don't use any
classes or cogs
it looks to i have to use cogs
no you dont, just refer to the link ryuga sent and remove self from the command functions, will work fine
@client.tree.command(description="Ban a user")
@app_commands.checks.has_permissions(ban_members = True)
async def ban(inter: discord.Interaction, member : discord.Member, *, reason: str):
try:
await member.send(f"You have been banned in {inter.guild} for {reason}, Would you like to appeal? Join this server:")
await inter.response.send_message(f"{member.mention} has been banned for {reason}")
except:
await inter.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
finally:
await member.ban(reason=reason)``` i need help adding a error response , so if user isnt mentioned it says a message
Guys, what is _pycache_
its normal dw about it , when u use python it just adds some cache
Okay, thanks
np
Catch the missing required argument in an error handler.
Understandable
in a slash command, it doesn't let you to run the command without entering the parameters
in sqlite db table, i have 3 users with some data on them. But i have for loop. Is there a way to make the bot not to spam?
this is my structure
Eventually append to a string and output as embed description/field depending on the layout you want
Just have them under eachother using fields
for i in data:
embed = discord.Embed(
description = f"..."
)
embed.add_field...
await ctx.send(embed=embed)```
this what i try to make
Do recommend keeping in mind the field limits
Put embed = and ctx.send outside of your loop
And the send under the for
soo
for i in data:
.....
await ctx.send(embed=embed)```
And embed = before the loop
Like the embed = discord.Embed thingy
oh
ok, so i should add this above the loop
correct
let me check it
im also making it as a prefix
what should i do
@slate swan a problem.... :\
embed = discord.Embed()
for i in data:
embed.add_field(...)
embed.add_field(...)
await ctx.send(embed=embed)```
Right ?
I guess
One field is enough
Just use the title kwarg as well
Unless they shrink name and hours of the staff member together
let me send screenshot
that what im talking about
and i try to make list, you know
yeah you gotta make some cleaner list
something like Name / Hours or similar
I try to make something like
Staff Name: Staff Hours:
(mention all users from the table) (send data from table)
Yeah as i said
gotta make the list differently
Cna i creat / command whit python bot?
I persian
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
to something like
Staff Name / Staff Hours
@slate swan / 1337 hours
@slate swan / 7331 hours
yeah but how can i make staff name to be next to staff hours in description?
just make sure it respects the chars limit
!e
desc = ""
for i in range(0, 10):
desc += f"{i}\n"
print(desc)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
007 | 6
008 | 7
009 | 8
010 | 9
!dum
Dunder methods
Double-underscore methods, or "dunder" methods, are special methods defined in a class that are invoked implicitly. Like the name suggests, they are prefixed and suffixed with dunders. You've probably already seen some, such as the __init__ dunder method, also known as the "constructor" of a class, which is implicitly invoked when you instantiate an instance of a class.
When you create a new class, there will be default dunder methods inherited from the object class. However, we can override them by redefining these methods within the new class. For example, the default __init__ method from object doesn't take any arguments, so we almost always override that to fit our needs.
Other common dunder methods to override are __str__ and __repr__. __repr__ is the developer-friendly string representation of an object - usually the syntax to recreate it - and is implicitly called on arguments passed into the repr function. __str__ is the user-friendly string representation of an object, and is called by the str function. Note here that, if not overriden, the default __str__ invokes __repr__ as a fallback.
class Foo:
def __init__(self, value): # constructor
self.value = value
def __str__(self):
return f"This is a Foo object, with a value of {self.value}!" # string representation
def __repr__(self):
return f"Foo({self.value!r})" # way to recreate this object
bar = Foo(5)
# print also implicitly calls __str__
print(bar) # Output: This is a Foo object, with a value of 5!
# dev-friendly representation
print(repr(bar)) # Output: Foo(5)
Another example: did you know that when you use the <left operand> + <right operand> syntax, you're implicitly calling <left operand>.__add__(<right operand>)? The same applies to other operators, and you can look at the operator built-in module documentation for more information!
You can
I'm adding cog from other file stats and roll commands are duplicated
maybe you created the commands with global scope first and then guild wise, or vice-verse
other file just contains 2 command which are roll and stats
just purge all the commands once
class BitikBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix="!", intents=discord.Intents.default())
self.count = None
async def setup_hook(self) -> None:
await self.add_cog(fun.Fun(self))
await self.add_cog(MySlashGroupCog(self))
self.tree.copy_global_to(guild=discord.Object(id=993917768757940224))
await self.tree.sync()
async def on_ready(self):
live_counter.start()
print(f"We are logged in as {self.user}")
As said above, purge them all once
in the error handler for the prefix command, check if the error is instance of MissingRequiredArgument then do something
You probably have a guild command and a global command
class Fun(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.mongo_client = pymongo.MongoClient("")
self.col = self.mongo_client[""][""]
@app_commands.command(name="roll", description="Zar yuvarlar.")
@app_commands.describe(dice="Maximum değer giriniz.")
async def roll(self, interaction: discord.Interaction, dice:app_commands.Range[int, 1, None]=10):
await interaction.response.send_message(f"{random.randint(1, dice)}")
@app_commands.command(name="stats", description="Sunucu istatistiklerini gösterir.")
async def stats(self, interaction: discord.Interaction):
print("asdjujklasşdaskdjıokpaslğspkojıduh============================")
if self.col.count_documents({"_id":interaction.guild_id}) != 0:
print("eski kayıt")
await interaction.response.send_message("test")
else:
print("ynei kayr")
await interaction.response.send_message("test")
Ok
Btw guys I wanna learn python myself and stuff, can someone refer me to any good videos or something, I want to be a professional
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
corey schafer
?
hes a youtuber who has great python tutorials
Could I possibly learn quite a lot and make stuff eventually?
Welcome to my Channel. This channel is focused on creating tutorials and walkthroughs for software developers, programmers, and engineers. We cover topics for all different skill levels, so whether you are a beginner or have many years of experience, this channel will have something for you.
We've already released a wide variety of videos on to...
Who couldn't
if you want to learn faster, try codewars or something
Ok
I don’t care even if it takes like couple of months
As long as I can learn alot I’m down
how i prevent it
Follow your status
Just takes time
You already got told, purge the commands once and start the bot again - then see if it's still the same.
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(inter: discord.Interaction, member : discord.Member, *, reason: str):
try:
await member.send(f"You have been banned in {inter.guild} for {reason}, Would you like to appeal? Join this server: ")
await inter.response.send_message(f"{member.mention} has been banned for {reason}")
except:
await inter.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
finally:
await member.ban(reason=reason)```would this work for a prefix command
There's no error handler so yeah
I recommend trying hybrid commands
Probably not working as you want it to work
Since this won't work
I’ll add a error handler for the ban command
prefix commands don't take an inter, they take context
The first paremeter is a discord.Context object, but try hybrid commands as said above.
Aha ok thanks for letting me know, discord.py 2.0 has been killing me and I forgot sorry
😭*discord.ext.commands.Context
ok.
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
Btw for prefix cmd do I do reason= None or just reason: str
Is none else it's a required keyword arg
doesn't change
Ok
Wait so how should I do a error handler for the ban command
also , py @client.command(name="sync") async def _sync(ctx: commands.Context): client.tree.copy_global_to(guild=discord.Object(id=)) await client.tree.sync() how can i make this global for slash commands , im making a public bot
Are trying to create a slash and command bot that have the same commands?
ye
prefix and slash
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
This is both a prefix and slash command discord.py made this so you won't have yo do things twice.
omg so it will form a prefix and slash command?
Is it possible for discord.Message.content to select a certain str? ex. discord.Message.content(1)
Yes lol I'm trying to explain that to u for the last 3 min
how do i impoort and use show me exampole
You mean select a word?
I can't make an example rn I'm on phone
client = commands.Bot(command_prefix = '!', intents=intents)``` do i have to change this?
yeah
split the string and take the argument needed
import deez
That's how to import
unfunny
Really? I thought it's hilarious!
good for you, but were here to help with discord bots and not go ot :))
I was teaching how to import
@slate swan could you explain hybrid to @warped mirage I'm on phone ;-;
im not very experience on using hybrids havent even checked docs for it, im on phone
im making a bot for translation (not a translate bot (fr->en) and i want to have multiple words (ids) but not have a command for all of them
example: tv!translate es 3 Hola
<lang> <id> <new translation>
i am trying right now using if functions
use commands
not the on_message event
i kinda stopped bot dev before the timeout endpoint was even a thing
Ok
btw my code:
@bot.command()
@translator_only()
async def translate(ctx):
if discord.Message.content(1) == 'gr' or 'el':
await ctx.reply("Greek selected")
if discord.Message.content(1) == 'bg':
await ctx.reply("Bulgarian selected")
if discord.Message.content(1) == 'es':
await ctx.reply("Spanish selected")
Use paremeters
Is learning async necessary?
See this
I picked it up again I want to create something special for a private server.
For Discord Bots
bot dev just became boring imo
Yes.
Anyone
now im in networking 
again yes
Yes, anyone responded @smoky marsh
with python?
Also doing that I'm combining the 2
Any recommended resources?
Do I need to like fully learn it or only know what it does
im taking a networking course thats 70 hours long and is pretty general talk of networking lol
Damn.
you use Go for the matter right? you work with cyber security which you would need to know networking i assume
Name every single network protocol
yuh
😨
what do u do with networking?
Network
🔥
well basically everything related with networks e.g NFC Bluetooth and wifi
Okimii making his own network protocol
why exactly may i ask?
This series of videos introduces AsyncIO to Python programmers who haven't used it yet. The first episode is a high-level view on the async ecosystem. We cover:
- why you'd want to use asynchronous code at all;
- how latency drives the user experience;
- what the difference between concurrency and parallelism is;
- some of the problems you can...
interesting
this series is actually really nice
i wouldnt even remember it
i love it ngl
well, mostly for network security itself
Only this video or the whole serious
well i mostly saw on google that python java and iirc js are used for network im not quite sure as im still learning the concepts of basic general networking
thumbnail seems way to happy about asyncio
the whole series:))
Very great bright guy non the less
Damn, this is why I hate my life. Anyways, thank you
i mean py is also good, just hate py sometimes so yuh
Its quite fun youll like it!
Lmao
Okay, thank you
He's Python's Developer in residence!! And also in this server
i might watch it to get time pass faster
i would agree but to be honest py is the only language i see my self using for production work idk why
mhm nice
That series is just so huge
yeah probably because you have more knowledge
from where are u doing this some yt tutorial?
70hr long
its like a web article
link?
personally i always try to not go on youtube for any coding tutorial or explanations, usually horrible
yeah same, but more often blog articles or something similar before SO
im currently network protocols and architecture
they even have questions and modules pretty fun ngl
and labs !
made by cisco hmm
probably some advertisement at the end of the course on how to setup a network with cisco router or similar
they even show how to make a network with a packet tracer which is cool
nah its a whole module on how to make a network with cisco😭
at least it's interactive
but its free so give it a chance yk
How much did u payed it for
expected
0
free 99
oki is prepared for codejam
it has videos, labs, tests and modules for each module of a topic so yes
he will carry his team
can u give me the site link pls then 😃
that's good
im just learning networking cuz ive always liked it and i want to start early so ill be experienced in college
cool
but you will carry 😳
college yuck
only practice ive done for cj9 is making a chat app with Websockets and an API
👀 wow
which i havent finished cuz of my course and i made some calculations with 70 hours i would need to atleast do like 5 hours a day to not be reading the whole course for a month
@slate swan am i the only one that has a stroke remembering network protocols😔 😭
don't need to know every single one
the most useful/used you will learn them with the time
who said i didnt🤨 😳
Me
exercises etc. will help you remember the most important ones
yeah to me its easier to learn them when its implemented in a problem
🔪
can someone teach me how to use hybrid commands
or, how to make a ban error function for missingRequiredArgument]
@bot.command()
async def banlist(ctx):
guild = bot.get_guild(971542589859844136)
list = [515131107696443393]
for item in list:
await guild.fetch_member(item)
return
for user in list:
if user == bot.user:
continue
await user.ban()```Can someone help?
no error or runtime error
just doesn't work
channel ids in discord are ints or strings?
ints
snowflakes
theyre unique integers referenced/represented as snowflakes
so what's wrong here
return breaks out of the function, so after the first loop, it leaves the function
!e
def foo():
return
print('hi')
foo()
@paper sluice :warning: Your eval job has completed with return code 0.
[No output]
!d return
7.6. The return statement
return_stmt ::= "return" [expression_list]
``` [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) may only occur syntactically nested in a function definition, not within a nested class definition.
If an expression list is present, it is evaluated, else `None` is substituted.
[`return`](https://docs.python.org/3/reference/simple_stmts.html#return) leaves the current function call with the expression list (or `None`) as return value...
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'ban'
that's the error now
@bot.command()
async def banlist(ctx):
guild = bot.get_guild(971542589859844136)
list = [515131107696443393]
for item in list:
await guild.fetch_member(item)
for user in list:
if user == bot.user:
continue
await user.ban()```
you didnt assign this
await guild.fetch_member(item)
can I append it to another list?
okay so i need a little help here.
how can i check all messages sent in the last 10 minutes in a channel and delete them if they have a certain word?
sure
you can just ban by ID
await Guild.ban(discord.Object(id=<ID HERE>))
also don't name your variable as list, its a builtin
data = []
for item in list:
data.append(await guild.fetch_member(item))```
like this?
@tasks.loop(minutes=10)
async def iAmAnIdiotPleaseHelpMeThankYouVeryMuch(ctx):
e = bot.get_channel(id)
```
It does get quite interesting, but also the nitty gritty of it is not fun. 2 sided blade, if you will
does anyone mind
message moderation is usually done by checking messages as they're sent, but if you want to do it like that you can use the text channel's history() method and provide a datetime 10 minutes in the past to the after= kwarg
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
What is the shortest async tutorial lol
How much async io knowledge is required for discord bots
yo , are u decent with dpy 2.0?#
I like to think that I am, yes
A decent bit can help you understand what's going on under the hood and diagnose possible errors yourself
I would go a bit more than the bare minimum
i would agree, but to me its like a single bladded sword, you just have to go with its flow 😳
How do I make the command so I can access it on discord with any big and small letters?
Like the command name is "hello" and I write !heLlo
you can have aliases or make your bot case_insensitive
🗿 why not the case_insensitive arg in Bot?
or make your bot case_insensitive
@bot.command()
async def addData(ctx, value, amount):
``` - how is this made accessible by any form of the command name with big and small letters
Pass in case_insensitive=True to your bot's constructor
(I hope it's true and not false, I'm having a hard time thinking about it lol)
Don't know why they didn't just call it case_sensitive: bool but whatever
its True
you pass true and it would make it case insensitive if you pass false it will make it case sensitive
if isinstance(error, commands.Forbidden):
await ctx.author.send(f"Missing Perms {error}")
is this right way to check and send a missing send message perms for the bot?
Yes.. but do you really want to send it as a DM to command runner?
Because that in itself could raise an error, if they have DMs turned off
I'm not sure how discord.py handles errors inside error handlers
idk where else to send the message
should i use nested loop?
or just log it in a txt or smth?
role_ids = [123, 456, 789]
await member.add_roles(member.guild.get_role() for role_id in role_ids)
It's either that or
await member.add_roles(*[member.guild.get_role() for role_id in role_ids])
Sends them to on_error
Just pass *roles if you already have the roles object in a list, I believe that works
is that an event decorator?
!d discord.ext.commands.Bot.on_error iirc
await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default error handler provided by the client.
By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error "discord.on_error") for more details.
Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
Not a deco
Seems like a fantastic way to get recursion issues
i need help with 2 things
The errors from on_error don't go to that function as of my experience
one , py @client.command(name="sync") @commands.has_permissions(administrator = True) async def _sync(ctx: commands.Context): client.tree.copy_global_to(guild=discord.Object(id=)) await client.tree.sync() first of all im making a public bot , how can i make this a global command? its to sync slash commands
Is it not already global? Seeing as it's a regular prefix command
utils/bot.py lines 106 to 108
async def on_error(self, event_method: str, *args, **kwargs):
self.log.error("Unhandled exception occured at %s", event_method)
await self.log_error()```
Well yeah the whole point of the function is to copy global app commands to a specific guild
i want it so that it works in every guild , is it possible ? or mah
That depends on what you pass in to your slash command constructors
Yes. If that doesn't work try the 2nd method
wdym
I don't think you can get what permissions bot is missing when it gets 403
I think it's possible only with local checks
so its impossible to make multiguild bot with slash commands?
!d discord.ext.commands.bot_has_permissions for example
@discord.ext.commands.bot_has_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions "discord.ext.commands.has_permissions") except checks if the bot itself has the permissions listed.
This check raises a special exception, [`BotMissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BotMissingPermissions "discord.ext.commands.BotMissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
im asking not saying
How do you think most of bots with slash commands work like dank memer, dyno etc
It's possible ofc
Just dpy 2.0 became user unfriendly
so for dpy 2.0 currently not possible?
can someone here help me
I mean I can if I do some research
You can do list comprehension with a * and use discord.Object
member.add_roles(*[member.guild.get_role(rid) for rid in role_ids])
k
sarth , u good with dpy 2.0 lol
🚶♂️ i don't even like that + its just a basic python thing
updated the message already
it should be get_role
@warped mirage could you show your code once again and what do you want it to do
ok
@client.command(name="sync")
async def _sync(ctx: commands.Context):
client.tree.copy_global_to(guild=discord.Object(id=))
await client.tree.sync()``` first of all i want to make this multi guild , syncing , i want the slash commands to work in every guild
no problems
And what happens
you want it to work in all servers?
yes , im making a public bot
just don't use the copy_global_to then
do i remove that line?
if you pass in a guild ID when creating a slash command, then it will work only in that guild. If you don't pass it in, then it's a global command and will work in all servers. The only problem is that it can take up to 60 minutes for it to propagate
Just use disnake
i'd agree with exenifix 😔
@client.command(name="sync")
async def _sync(ctx: commands.Context):
await client.tree.sync()``` so like this?
slash command registration is instant now 
Like I mentioned before the whole point of copy_global_to is to copy your global commands to a single guild. I don't see why you need to do that if you want to make a bot that works in all guilds
so is that correct? ^^^
To sync, yes
I approve of this message™️ 
i think so, try it and see
ok last thing i need help with
Though I don't really see the point of having a syncing feature on command
Might as well just put it on_ready or something similar
slash commands wont work then
im hating the discord api more and more :V
Sync it on_ready or something similar, like mentioned
can u show me how
when you realise slash subcommands are just slash command options
@client.listen()
async def on_ready():
await client.tree.sync()
or the setup_hook would be even better!
I believe that happens before the websocket is fully connected?
Don't know if that matters for a REST operation like sync()
it doesn't, thats purely a HTTP method
I figured nothing wrong with syncing multiple times, and people are more used to the on_ready anyway
In that case setup_hook should be fine
like this?
mhm the github example suggests so
ok
You might as well move it into your existing on_ready
And move your change presence into a task while you're at it
like this?
oi man, thats a bad way to change presence
check this out > https://gist.github.com/Okimii/0b6e5dcfcfb895ef613ac59a4ecc096a
No, outside your while True loop
Which shouldn't be there in the first place (discord.ext.tasks)
This was excellent
thanks to Oki :D
Eyup. Once I'm back from this little break I'm going to finish up anything that needs to be done on that and get it merged onto site, and maybe get a !tag for it on the bot as well
yeah that would be great since there are many beginners who just change the status in on_ready calls
As evident here haha...
check the link you have been redirected to
😳
would this just work?
yeah dont.
well then tell me how or what to do
should be changing it like evvery 30 minutes and in a task
no i need it to be updated ever 15 seconds
i'd recommend something else.
whole point lol ]
im so confused . ill need help..
well you're screaming for your bot to be banned :))
wdym by banned
as bluenix has told me, discord doesn't like it when you change your presence each certain amount of time, so discord closes the ws connection or ban you iirc per internet protocol
your bot
bro my friends bot is verified , 560 servers and it updates every 5 seconds
some bots have bigger ratelimits depending in size and i doubt it lol
ok then can u help me fix each thing
because your friend jumps out of a cliff doesnt mean you should as well
ok then help me please.
i would probably go for the solution sarth has recommended
not really
.... i need to know how many servers my bot is in... multiguild#
live count
you can probably check the current amount of guilds and then when the event gets dispatched you add a value to the global variable e.g 1 for 1 more guild
then you can change your bots presence but not in a certain time frame
can u help me then please
maybe getting a random time frame like 20mins to 40mins
so it updating every 40 mins?
!d random.randrange
random.randrange(stop)``````py
random.randrange(start, stop[, step])```
Return a randomly selected element from `range(start, stop, step)`. This is equivalent to `choice(range(start, stop, step))`, but doesn’t actually build a range object.
The positional argument pattern matches that of [`range()`](https://docs.python.org/3/library/stdtypes.html#range "range"). Keyword arguments should not be used because the function may use them in unexpected ways.
Changed in version 3.2: [`randrange()`](https://docs.python.org/3/library/random.html#random.randrange "random.randrange") is more sophisticated about producing equally distributed values. Formerly it used a style like `int(random()*n)` which could produce slightly uneven distributions.
Deprecated since version 3.10: The automatic conversion of non-integer types to equivalent integers is deprecated. Currently `randrange(10.0)` is losslessly converted to `randrange(10)`. In the future, this will raise a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError").
its not random lol
can u please help me then or no?
you can ig change your presence on each guild join without anything that would do fine ig
can u update this for me.
@client.event
async def on_ready():
await client.tree.sync()
while True:
await asyncio.sleep(15)
await client.change_presence(status=discord.Status.online, activity=discord.Game(f"!support | Im in {len(client.guilds)} Servers"))
print("Online")
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
and just change the presence inside of the function
idk how
its a namespace just name a function with that name so when the event gets fired the function gets internally called, hence why i told you to change your presence inside of it
i have guided you 
can commandTree.on_error works with app_command
no
i said i need it to change lively
u didnt in which way i need..
Robin, Sarth and me have helped you, if you cant figure it out maybe you should check out resources
I helped you the way it should be done.
bro i need it to be updated,..
by guiding you to learn and try hard and not be given everything. I am encouraging what this server stands for.
then how come wick and those bots have live counts, but i cant??
^
seperate event?
What the what is that while True
so currently , every 15 seconds it updates the server count
Also updating status every 15 seconds might get you ratelimited
wtf it changed , my bot restarted like 7 times
that is so, the whole feature you want can be done in easily 3 lines.
never had this before
!d discord.ext.tasks.loop use this instead of while True + asyncio.sleep
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
no
Also increase the duration, 15 seconds like mentioned is way too short
Maybe a minute to be courteous
my bot restarted 7 times with the current code i have , not good ig
Or use on_guild_join
And if you are trying to change presence when the bot joins a guild it shouldn't even be connected to any events it should be in a loop as well
can u help me with that?
I usually have it at 30 mins
btw if its 30 mins , does ur bot restart after 30 mins?
it really shouldnt be a certain time span lol
The function is called every 30 mins
well if u wanna have a live count that would be nice
Yeah whoever needs 100% accurate amount in status
nah i can make mine every like 30 mins i guess
just use on_guild_join
@client.event
async def on_guild_join():
while True:
await asyncio.sleep(30)
await client.change_presence(status=discord.Status.online, activity=discord.Game(f"!help | {len(client.guilds)} Servers"))```
Imagine bot joining 5 guilds at once - 5 useless API calls and ratelimit
@bot.event
async def on_guild_join(guild: discord.Guild) -> None:
await bot.change_presence(...)
its this easy
Imo it's better to update the amount once in certain interval, not on every guild join
better?
If you care about live accuracy then on_guild_join if about amount of requests then tasks.loop
it shouldnt be a certain interval and guild_join can be called many times but you can probably just have a ratelimit or something
bruh then how can i make a livecount , i need one
its literally right here
well then you have it
it wont update until your bot is added again into a new guild
I mean this
@tasks.loop(minutes=30)
async def update_stats():
await bot.change_presence(activity=Idk(len(bot.guilds)))```
as told in the namespace description
ye but then i can get ratelimited right?
iirc ratelimits for dispatching events is like 120/120s
iirc?
if i remember correctly/if i recall correctly
wdym? so how long do they last
you would only get ratelimited if you surpass the limit
which its 120/120s or 60/120s im not sure
how long do u get ratelimited for? if so
about an hour which i doubt would happen.
if you hit a rate limit you'll just get an error
ok uknow what.
if you abuse rate limits too much your bot gets temp banned
@slate swan ill do what u suggest. i just want my bot to be fine
then with what i recommended it would probably be fine lol
@client.event
async def on_guild_join(guild: discord.Guild) -> None:
await client.change_presence(status=discord.Status.online, activity=discord.Game(f"!help | {len(client.guilds)} Servers"))
``` so this ye?
yep
wait a sec
@tasks.loop(minutes=60)
async def update_stats():
await bot.change_presence(activity=Idk(len(bot.guilds)))``` should i add this or na
no need
That's pseudocode anyway
ok, btw if this will be a big problem can i do a command that checks how many servers the bots in? if thats easier
yeah you can
ok so im sorted ig
Checking amount of guilds is just len(bot.guilds) and len just does simple division not even an expensive operation
just send the length of client.guilds
ye
last thing then
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason: str):
try:
await member.send(f"You have been banned in {ctx.guild} for {reason}")
await ctx.response.send_message(f"{member.mention} has been banned for {reason}")
except:
await ctx.reply(f"The user you are trying to ban has DM's closed", ephemeral = True)
finally:
await member.ban(reason=reason)``` how can i add a missingRequiredArgument error for this prefix command
nvm you ment argument and not perms
ye
but a local error handler would be what you want
Just handle it in error handler
so i can do it for any command that needs argument and send one message and it will do it for every command?
just catch all errors in a local error handler and check the instance of the error with an isinstance
Why local
well it depends if he wants to do special tasks with that certain error triggered by that command
all i want is
Yes
currently all i want is that any command that requires an argument will send a error reply ephemeral saying , You must specify a username
Ephemeral can't be sent without an interaction
well Context doesnt have ephemeral messages but an error handler is what you want
wait forget ephemeral
i can just do delete_after = 10 ?
it depends on what you want
well i said what i want lol
you just said can i use a kwarg ofc you can use the kwarg lol
well
nothing is limiting you but i just ask because it depends on what you want really
so any command that is missing a argument , it sends a reply that it needs to specify a username , then it gets deleted after 10 seconds
Global error handler does that
any or one command?
well any then since i have mute command and them it will be easier ig, but whatever u suggest
read the gist it shows you have to make an error handler to deal with that
then on_command_error would do you good
it's commented to explain most of it as well
how can i do
you can just use the name space to redirect the traceback
hmm
Why are people still chaining elif isinstance(error, SomeErrorClass) repetitive code 🤓
how can i do it fully]
cant you use match and case?
Dict with error classes as keys and values as responses and there you go
Looks much cleaner
!d discord.discord.ext.commands.on_command_error
discord.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://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
if all youre going to do is send a message yep that would be better
idk how to make it lol
I have it like some errors derive from my custom class and they have action method so instead of just sending a message they do the action and send the message
if anyone can please help
I forgor where I used it tho
nice
Simple Error Handling for ext.commands - discord.py - error_handler.py
its an event and namespace
you would decorate it with Bot.event and use the namespace as your function name so it can be called internally
Idk you
You sure
Prolly not
looks like we had dm history
events dont pass ctx
that one does
it passes the Context and error of the command that had the error
How many lines does python fetch
probably like 10
utils/errors.py lines 158 to 165
try:
missing_perms = ", ".join([str(perm) for perm in error.missing_permissions])
except AttributeError:
missing_perms = None
try:
missing_roles = ", ".join([str(role) for role in error.missing_roles])
except AttributeError:
missing_roles = None```
These are cringe
come in dms for a sec
🧍
what have you tried
Please read the gist
That's not how it's formatted in the gist
..
u forgot a colon btw
And understand what is written*
@client.event
async def on_command_error(ctx, error: Exception):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("enter your string etc")`
#etc etc
hes not in a cog
i copied it from the gist mate.
@client.event
async def on_command_error(ctx, error: Exception):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'Please specify a username.')``` does this work?
MasterDroid i would recommend you learn OOP, async programming and basic Python as discord.py is a lib that utilizes OOP and asynchronous code, you have been given many sources but have had trouble due to your skill level, sometimes learning a topic over going to the advanced part of it is the best thing to do in order to learn better.
It should but keep in mind that'll run for every command that hits a missingrequiredargument error
Nice
A local error handler might be better in certain cases
if dpys docs cant help you im not sure what can😅
will it worked tho what i showed
ye it will
im pretty sure your annotations arent correct and try out and see
Would the "Guide how to host a python discord bot with docker and github actions" be a useful tutorial
Useful, yes. Not sure how much it'd be read considering people seem to use replit or heroku most of the time, and on the off chance someone is hosting off an actual cloud service, they usually just install python and run their bot
Definetely useful for the people looking to go one step further, though
Ok
im making a bot with my friend and i added a rate command where it will pick a random number form 1 to 6 and rate the subject arg that number, but im getting an error, heres code:
from discord.ext import commands
import os
import asyncio
import random
from typing import Optional
import time
from discord.ext.commands import cooldown, BucketType
class RateCommand(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.last_msg = None
@commands.command(name="rate")
async def rate(self, ctx:commands.Context, *, subject):
if not ctx.guild is None:
#await asyncio.sleep(random.randint(0,2))
rateValue = random.randint(1, 6)
embed=discord.Embed(title=" ", description="** **\n** **", color=0xfffff0)
if rateValue == 1:
bar = "🟥⬛⬛⬛⬛⬛"
emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935005847683/unknown.png"
if rateValue == 2:
bar = "🟥🟥⬛⬛⬛⬛"
emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935005847683/unknown.png"
if rateValue == 3:
bar = "🟥🟥🟧⬛⬛⬛"
emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935341379625/unknown.png"
if rateValue == 4:
bar = "🟥🟥🟧🟧⬛⬛"
emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935341379625/unknown.png"
if rateValue == 5:
bar = "🟥🟥🟧🟧🟨⬛"
emoji = "https://cdn.discordapp.com/attachments/996551788423565424/997620935739854928/unknown.png"
if rateValue == 6:
bar = "🟥🟥🟧🟧🟨🟨"
emoji = hhttps://cdn.discordapp.com/attachments/996551788423565424/997620935739854928/unknown.png
embed.add_field(name=bar, value="** **", inline=False)
embed.set_author(name=f"I rate {subject} {rateValue2.", icon_url=emoji)
await ctx.reply(embed=embed)
def setup(bot: commands.Bot):
bot.add_cog(RateCommand(bot))
and error:
Traceback (most recent call last):
File "/home/runner/Duck-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 839, in exec_module
File "<frozen importlib._bootstrap_external>", line 976, in get_code
File "<frozen importlib._bootstrap_external>", line 906, in source_to_code
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/runner/Duck-Bot/commands/rate.py", line 41
emoji = hhttps://cdn.discordapp.com/attachments/996551788423565424/997620935739854928/unknown.png
^
SyntaxError: invalid syntax
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "main.py", line 14, in <module>
bot.load_extension("commands.rate")
File "/home/runner/Duck-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/home/runner/Duck-Bot/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands.rate' raised an error: SyntaxError: invalid syntax (rate.py, line 41)
its only line 41 tho
You forgot the quotes also if chain is a bad idea
Check this out https://youtube.com/shorts/UFdEp9wrtOY?feature=share
Avoid endless if-else statements with this Python Tip!
⭐ Join Our Discord : https://discord.gg/FHMg9tKFSN
📓 ML Notebooks available on Patreon:
https://www.patreon.com/patrickloeber
If you enjoyed this video, please subscribe to the channel:
▶️ : https://www.youtube.com/channel/UCbXgNpp0jedKWcQiULLbDTA?sub_confirmation=1
Just the principle
You could do bar like this as well ig
full_bar = "🟥🟥🟧🟧🟨🟨"
print(full_bar[:value] + "⬛" * (6 - value))```
!e py value = 3 full_bar = "🟥🟥🟧🟧🟨🟨" print(full_bar[:value] + "⬛" * (6 - value))
@vale wing :white_check_mark: Your eval job has completed with return code 0.
🟥🟥🟧⬛⬛⬛
It's DRY code
You should just be able to look at it and tell
Notice how you're repeating the same thing over and over again? Usually that's a bad sign
Their code is actually WET isn't it
down bad bro
Is member.avatar_url removed in discord.py 2.0
property url```
Returns the underlying URL of the asset.
uhh how can I make it to where the reaction is on the sent message?
@commands.command(name='poll', description='Creates a poll')
async def poll(self, ctx, *, question):
"""Creates a poll."""
await ctx.send(f'{question}')
await ctx.send('React with the appropriate emoji.')
await ctx.message.add_reaction('👍')
await ctx.message.add_reaction('👎')
await ctx.message.add_reaction('❔')
i mean the message that the bot sends showing the question
which channel has tutorials
have you tried "pip install poetry lock" ?
message = await ctx.send(...)
await message.add_reaction(...)
.bm
Thanks
Is there a way to add space between 2 words in embed description ?
like Word1 Word2
and i want Word1 Word2
Hello _ _ _ _ _ _ world
Hello _ _ _ _ _ _ world
yeah
That should work I guess
i just want to add some space between 2 words
underscore?
Yeah then use _ _ per space
underscore space underscore
ok but are you sure this will work in description of embed?
It should
Formatting is the same as normal messages
i think \u200b should work too but im not sure
the underscore didnt work
this didnt work too
love discord
What account
If you mean yours, it's a selfbot
Against Discord ToS
'\u200b ' * some number should work as a gap, but its a janky solution
!rule 5
Okay ty
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
can get your account terminated quite easily
do you refer to me?
nana
Oh ok
other person that deleted the message
i got a heart attack for a sec
question, how do you get a bot to say stuff at specific intervals like every minute
AND how do you get a bot to say specific stuff based off a chat command with no trigger (like having to say stuff to toggle)
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
what about the second question
on_message probably
Is there a way the bot to send only 10 values in embed so i can make embed pages
For example, i have selected a table list from sqlite file, which 20 values and i want on the first page to be only 10 and on the second page, the rest of the values (20)
Some level of JS is going to be required
It's not too terribly difficult, I've done it easily. Only with a framework though (for my dashboard)
Sure.. are you having any specific issues?
Uh yeah I suppose you could ping me
What is considered the "bare minimum"
this seems interesting, what do you need for this?
It's.. hard to quantify. Knowing enough to know how to use it I might classify as the bare minimum
what do you need for this?
do you mean what features do I have that require a log in with discord?
no i mean like, how do i access the log in thing itself, is it part of the api or ?
You go through the Oauth2 API flow which is documented here: https://discord.com/developers/docs/topics/oauth2
With a little bit of effort from the developer, the user facing side can be really easy. I'm talking 2 clicks to log in with your discord
oh nice, thanks
Yep. I encourage you to implement it yourself, even something that prints out the user's guilds to the JS console and have them go through Oauth2 just to get a feel for how it works
So, what do you recommend me to learn in order to have enough to make discord bots?
I believe there was a realpython on asyncio, reading through that and making sure you understand all of it is a good step in the right direction
No, it's all done with your actual discord account
right will do 👍
Reading through all of that...?
If you successfully go with the oauth2 flow, you should have the user's token that you can use for REST operations
Yeah I'm here everyday, just send a ping my way and if I'm there I'll see what I can do
https://realpython.com/async-io-python/
Is this the tutorial you're referring to?
Yeah, that one
Understandable, thanks
I took it down after a while. Wasn't used much and I was primarily doing it for the learning experience, so sadly it isn't up anymore
This is a bad idea, you're going to get rate-limited
Is your command only supposed to ping a person once in the same channel that they ran the command in?
You're on the right track for that, bot.get_channel() only takes one ID at a time however
Traceback (most recent call last):
File "C:\Users\HP\Desktop\Discord Bots\discord_bot1.py", line 4, in <module>
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content' ```
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user and message.content.startswith('$hello bot'):
await message.channel.send(f'Hello {client.user}')
client.run('no')```
You're probably on discord.py v1.7.3
How do I fix it
Is the discord docs out of date or something
The discord docs are on the latest version, which you're not
https://github.com/Rapptz/discord.py#installing follow the development version instructions as outlined here
How do I update it?
https://discordpy.readthedocs.io/en/stable/api.html these ain't on the latest version
Ahh okay, thank you
I'm on 1.7.3
Guessed as much
I ran the command py -3 -m pip install -U discord.py and it says requirement satisfied
pip uninstall discord.py and reinstall
yeah it isn't on pypi
@cold sonnet What?
pip install -U git+https://github.com/Rapptz/discord.py
discord.py isn't on the latest version on pip
you have to install it from github
Installing it from pypi will always give you 1.7.3, yeah. Which is why I linked you to the install instructions on github
Ohh okay
gta6 is coming out first than dpy 2.0 on pypi and thats for sure
lmao
C:\Users\HP>pip install -U git+https://github.com/Rapptz/discord.py
Collecting git+https://github.com/Rapptz/discord.py
Cloning https://github.com/Rapptz/discord.py to c:\users\hp\appdata\local\temp\pip-req-build-ool05mlr
Running command git clone --filter=blob:none --quiet https://github.com/Rapptz/discord.py 'C:\Users\HP\AppData\Local\Temp\pip-req-build-ool05mlr'
fatal: unable to access 'https://github.com/Rapptz/discord.py/': Could not resolve host: github.com
error: subprocess-exited-with-error
× git clone --filter=blob:none --quiet https://github.com/Rapptz/discord.py 'C:\Users\HP\AppData\Local\Temp\pip-req-build-ool05mlr' did not run successfully.
│ exit code: 128
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× git clone --filter=blob:none --quiet https://github.com/Rapptz/discord.py 'C:\Users\HP\AppData\Local\Temp\pip-req-build-ool05mlr' did not run successfully.
│ exit code: 128
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.```
👁️ 👁️
lol
what are you trying to do with this because it doesn't make sense from what I'm seeing
Ok I installed it
All of that needs to be in a string
What does await do?
Python doesn't natively understand SQL, so it needs to be inside of a string
cursor.execute("SELECT ... FROM ... WHERE ...")
passes a function
ah
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user and message.content.startswith('$hello bot'):
await message.channel.send(f'Hello {client.user}')
client.run('my_token')```
Did I use await in the right place
It runs a coroutine, and waits for the result. Hence the await. Massive oversimplification but it gets the point across.
I believe it also adds it to the event loop
So what's the difference between async and await
sooooo, inside of speech marks?
The code ends instead of running
async is used to define an asynchronous function, or a coroutine, while await is used to actually run and wait for the result of said coroutine
Right
oh
uhhhh where does the comma go?
It's still not in quotations
Python is really confused because you're basically writing another language inside of it
There we go, run it again
it's still the same
only the sql query, the parameters iterable doesnt have to be within the same string
Also I don't believe SQL lets you use spaces for table names?
its supposed to be like this
"query", (param, )
hmmm
And yeah good catch, didn't see the (user.id) part at the end
I always get ignored
you didnt type anything 
.
oh lol
To be fair you did kind of phrase that weirdly
what's weird in that
not exactly.
Probably just nitpicky but it implies that the parameters iterable can be in the same string, but doesn't have to
like this?
I assume they took it as a suggestion and ignored it?
Well, close, but the rest of your query still needs to be a string
no the whole query part is supposed to be one string like
"SELECT ... FROM ... WHERE ..."
cursor.execute("SELECT ... FROM ... WHERE ...", (...))
jesus, where do you find common sense
whattttttt
await calls the function and passes the function to the event loop giving control to the event loop so the event loop can manage all the current coroutines to have concurrency
oh wait
and (user.id) is an int not a tuple
it is a little confusing but (something) doesn't make a tuple but (something,) does
so add a comma inside those parens
you mean like
thats basically what await does, it awaits for a coroutine to finish in the event loop so the event loop can manage it concurrently
or just provide a list or set if it works
right
discord.py provides one of the best inbuilt command handler, why in the hell are you not using that?
best?
ok this good?
You can't use double quotes inside of double quotes without confusing python into thinking that the quote is done, you can either escape it (\") or use single quotes:
print("Did you know that you can have 'single quotes' inside double quotes? But not \"double quotes\".")
Now we're back at square 1. Your parameters need to be outside
Idk anything about this, I just copy pasted this code to see if it works
I'm talking about both source and user experience
danny is still trying his best to update the library even after archiving it for 6+ months, def doing way better than what any of us would have tbh ¯_(ツ)_/¯
I agree, yet expect more from someone like him who has been working on a widely used library for years.
And keeping the point in mind that discord.py focuses on simple abstractions, the app commands part kinda suck
ok now?
good thing about them is that it provides full control to the library user instead of doing the sync api calls itself, but it's not too hard to implement it in an easy way/optionally
my wifi had a stroke
There we go. Given SQL allows spaces in your table/column names you should be good
aight ty
disnake did that, and I like their implementation , tho I use neither
and it still says I forgot a comma somewhere
select social, credit, balance
he shits on forks but forks implemented slash better lol (some of them anyway)
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.
ow it's in options
what is the name of the table you are trying to get data from?
they have a kwarg which stops the lib from making the api calls itself
I maintain that the reason I believe app commands are the way they are in d.py is specifically to differentiate from the forks, not because there's a good reason, because they seem to be almost unanimously disliked
` for app commands registration
Social credit tracker
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('your token here')```
Is this up to date code?
yes
table names cannot have spaces, are these 3 different tables or just one?
Then why does it show Event loop is closed
ohhhhhhh
just one
show full exception
Event loop closed gives no idea
yup, so you will have to make a new table with a name which doesn't have spaces
ok that makes so much more sense, how do you get it to go offline?
Usually happens when the token is invalid
Maybe you forgot to actually substitute your token into
client.run('your token here')
```?
I actually did
do underscores work?
@sick birch I mean that I have put my token in there
yup
offline as in the bot?
yes
Okay, can we see the full error then?
where are you running the bot from?
If I'm to guess it's an intent issue
Your bot is requesting intents that you may not have enabled in the dashboard
But let's see the full error anyway just to be sure
Yeah sure
Visual studio code
closing the terminal should work
Hey @smoky marsh!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Ok yes
!paste use this @smoky marsh
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.
Hey @smoky marsh!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Yeah
Guessed right, haha
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
ok
What?
Also, is the discord docs really up to date?
Cuz this is the code I'm running in the 2.0.0 version
And it's exactly from the docs
it is
Yeah, but the docs will often leave out little things like that
But luckily the errors are usually descriptive enough of that to tell you what's wrong
So what do I do
What does the error tell you to do?
Let me find
aise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.



dpy has poor app commands design imo