#discord-bots
1 messages Ā· Page 713 of 1
i realised
someone took the time to copy and paste the python bots lol
@slate swan
you're good at copy and pasting
do you write code or is it all copy and paste?
š
š¤
š³
to earth
Dunno bro but it sure is better than yours that's for sure lmao
š
š¤
š
But it doesn't really matter if its just googled lmfao
š
That takes 0 knowledge and skill and it just flat out lazy
If you wanted to do that just use RedBot
well not lazy tbf
Actually yeah because you do have to still put together the code
hats off to kraots because he actually succeeded - copy and pasting the whole docs command is hard

So maybe not lazy but definitely not either skillful either

Soo 
do i have permission to expose you
About?
those things
Sure
My bot had slash with autocomplete for both first so idk what you'll expose so gl 
nvm actually
Night š
how do i split text
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
how do i make a command that can give and remove roles but it can detect whether the use has the role or not to determine if it needs to give or remove it?
I got you
!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.
1 sec
where do i add that
!d discord.Role.position to compare role potions
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
You may like using @has_permissions() check too
alr
@bot.command()
@commands.has_permissions(manage_messages = True)
async def addrole(ctx, role: discord.Role, member: discord.Member):
guild = ctx.guild
await member.add_roles(role)
await ctx.send(f'I succesfully added role {role} to {member}')
###########################################################################################################################
if member == guild.owner:
return await ctx.send("You can't give roles to the server's owner!")
elif member.top_role > guild.me.top_role:
return await ctx.send(f"This member's top role is higher than yours!\n\n{member.top_role.name} <-- {member.mention}'s top role\n\n{ctx.author.top_role.name} <-- Your top role")
elif member.top_role > ctx.author.top_role or member.top_role == ctx.author.top_role:
return await ctx.send("You cannot give roles to someone with a higher or equal role to you!")
elif member.top_role == guild.me.top_role:
return await ctx.send("This member's top role is equal to your top role!")
elif role == ctx.author.top_role:
return await ctx.send("You cannot add a role higher then your top role to yourself!")
u can check if a member has a role, by doing smt like if role in member.roles and if there's don't then add it
tysm
thx!
spoonfeed at its finest
wow
@bot.command()
@commands.has_permissions(manage_messages = True)
async def addrole(ctx, role: discord.Role, member: discord.Member):
guild = ctx.guild
await member.add_roles(role)
await ctx.send(f'I succesfully added role {role} to {member}')
###########################################################################################################################
if member == guild.owner:
return await ctx.send("You can't give roles to the server's owner!")
elif member.top_role > guild.me.top_role:
return await ctx.send(f"This member's top role is higher than yours!\n\n{member.top_role.name} <-- {member.mention}'s top role\n\n{ctx.author.top_role.name} <-- Your top role")
elif member.top_role > ctx.author.top_role or member.top_role == ctx.author.top_role:
return await ctx.send("You cannot give roles to someone with a higher or equal role to you!")
elif member.top_role == guild.me.top_role:
return await ctx.send("This member's top role is equal to your top role!")
elif role == ctx.author.top_role:
return await ctx.send("You cannot add a role higher then your top role to yourself!")
###########################################################################################################################
@bot.command()
@commands.has_permissions(manage_messages = True)
async def removerole(ctx, role: discord.Role, user: discord.Member):
await user.remove_roles(role)
await ctx.send(f'I succesfully removed role {role} to {user}')
brother
Bro
That's with the removerole too
nvm...
God bless š
Don't care
these kinda guys spoonfeed and expect to get spoonfeed lol
Not really
didn't ask
oh thatās not what i wanted to do š
You cannot check > or < with roles
i want to do it with just one command
I'm just here to help, if he would've specified he doesn't want code then I wouldn't of had sent it+he literally asked how to make the code
you're probably better of making it yourself
You cant do it with only one command
It has to be 2
yeah thatās what iām tryna do but i donāt know how to exactly do it
It's 2 different actions
you can do it with one
alright I'll tell you
iāve seen bots that can do it
Lmao bruh
imagine spoofeeding and failing
thanks man š
š
so u want to add a role in one command and remove the role in another?
i want them both in the same command. basically the command can also detect if the member has the role or not to determine to give or remove the role
check if the role is in member.roles, if not use member.add_role, if it is in their roles, use member.remove_roles
you can just check if the member has the role (role in member.roles) , if they have it use Member.remove_roles , if they don't use Member.add_roles
first get the role using the ID
role = ctx.guild.get_role(id)
now check if role is in member.roles, if it isn't then add the role. And if it is then remove the role
Not important
u can add roles like this
u wouldnāt need to get the role if u use role: discord.Role in the args
true
yeah
Internally it's still grabbing the role from cache otherwise making an API call
You can't just pop a Role out of thin air
where do i put this
i didnāt say u could
u wouldnāt need to get the role if u use role: discord.Role in the args
yea referring to him using guild.get_role
well u need to make it yourself, u won't get spoonfeed with the exact thing here. I told u the methods and how you should do it so use that
but if you hardcode the role object with get_role it would be limited to a single role
Using it as a arg to get from user will allow you to use any role
in your command
oh yeah mb
how do i split text
so like
Output: You said hello and lol```
Tyler already answered you right?
!e print("this is :: the text".split("::"))
oh i didnāt see sorry
np
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['this is ', ' the text']
@soft narwhal
why does it have brakets and a comma
because itās a list
It's a list , you splitted the string into a list of strings divided by ::
message.content.split(ā::ā)
first thing , if you are doing it with a command
Get off on_message events
else , what popleoma said would work for u
Donāt necessarily need the .lower() itās just habit
Trying to troubleshoot a tricky interaction between a class method in a discord.py cog and a dataclass attribute
So basically, what happens is as follows:
Async task is created as an object and stored to Server.task
when the final condition is reached the task instead calls itself (recursive) but this is called with self.take_turn() in this case
The problem is, the self.take_turn() is saved to the dataclass and when it tries to call self.take_turn() it looks for the take_turn() method in the Server dataclass object rather than in the cog mentioned above and thus cannot find it
How do I work around this?
alas this is beyond my reading comprehension
I'll try to explain it better
From this Iām assuming you donāt know how to get items from a list?
I have a cog which has a take_turn() method, it has a recursive call when it ends the iteration
async def take_turn(self, server):
for num in range(server.word_count):
await self.make_message(server, num)
else:
await self.pass_the_mic(server)
server.task = asyncio.create_task(self.take_turn(server))
and I have a dataclass Server object which has that task written to it by server.task in the above code
but the problem is when it tries to call itself and feeds in the self.take_turn(server) evidently it is calling the take_turn() method from the dataclass itself and not from the cog as desired so it is unable to find the method
consider "server" in the above to be an dataclass object which has the attributes word_count and task
so when it does server.task = asyncio.create_task(self.take_turn(server))
it is calling the self.take_turn(server) recursively
so it writes the task to call the self.take_turn() to the server.task attribute
but the server object does not have a take_turn method, only the cog does, and when it tries to call the take_turn() method from within the dataclass object it doesn't find the take_turn method and throws an exception
Sounds like you should use functools.partial and pass that instead
!d functools.partial
functools.partial(func, /, *args, **keywords)```
Return a new [partial object](https://docs.python.org/3/library/functools.html#partial-objects) which when called will behave like *func* called with the positional arguments *args* and keyword arguments *keywords*. If more arguments are supplied to the call, they are appended to *args*. If additional keyword arguments are supplied, they extend and override *keywords*. Roughly equivalent to:
```py
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
what is that?
With this you can 100% make sure that you call the func with the self representing the Cog
I am going to have to watch a video on that package
no
I really appreciate your help earlier by the way suggesting to make the Helper function the import for the other cogs
that was an excellent suggestion and you sir are a gentleman and a scholar
To retrieve items from a list you do
listname[where the item is]
for example
the stuff in the [] is an integer btw necessarily, it is the index of the item
starting with 0
!e
myList = [ābaconā, ācheeseā, ābobā]
myList[1]
!d discord
To work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
It's " , not ``
Mobile moment
Mobile moment indeed š
This would return ācheeseā just for reference
Indeed
whatās the variable for the user that did the command
like i want it to mention the user that did the command
the author attr?
idk what attr means but if it mentions the user that inflicted the command then yeah
message.author ? this what Iāve been using
ohhh thx
await ctx.send(ctx.author.mention)
thx
yw
is there any way I can choose a random channel from a guilds channels
this happened š
will that have the id or name
Is this not what you wanted?
use an f string
put it in an f string
oh Nevermind I see the beginning now
oh thatās right
lol
my bad 
Returns a GuildChannel object š
how do i make my bot record like mee6?
i feel like thatd be complicated
to do
use a database
@bot.command()
@commands.has_role(924841723753021490)
async def role(ctx, user: discord.Member, role: discord.Role):
embed = discord.Embed(description=f"(ctx.author.mention): Added {role.mention} to {user.mention}",color=0x2f3136)
await user.add_roles(role)
await ctx.send(embed=embed)
what did i mess up here? :P
ur using ( instead of {
yeah it should be inside curly brackets
ohh
tbh no clue how im new to py
thereās no voice receive for dpy yet. Youād implement something like yourself.
Also , just a suggestion
Add the role before sending the message
i think he means storing user XP etc
He's doing that
...
Nvm me
Doubtful. He literally means record. Mee6 while in vc can record audio.
kekw np
And save it and play it back.
Mee6 doesn't use pure discord.py
should rename the discord.Member typehint to member instead
member and user is different
I never said it did 
weird i never heard of that being a feature i guess i was wrong
mhm , they would have to do some api stuff themself right?
Or , nextcord is implementing it iirc
It was java or js that had voice receive
No python wrapper has fully implemented voice receive
Javascript has it already
since djs v12 ig
pycord has it afaik
@bot.command()
async def role(ctx, user: discord.Member, role: discord.Role):
embed = discord.Embed(description=f" {ctx.author.mention}: Added {role.mention} to {user.mention}",color=0x2f3136)
await user.add_roles(role)
await ctx.send(embed=embed)
@bot.command()
async def removerole(ctx, user: discord.Member, role: discord.Role):
embed = discord.Embed(description=f" {ctx.author.mention}: Removed {role.mention} from {user.mention}",color=0x2f3136)
await user.remove_roles(role)
await ctx.send(embed=embed)
for some reason it can only give them one role
but it canāt give them other roles
Pycord cloned a fork of discord.py that had semi implemented voice receive lol
what did i mess up cus it only works with ONE role
hierachy maybe
you're only passing one role 
i meant itās only giving them just one specific role
what
but if i try to give them some other role it doesnāt work
in a single try or multiple tries?
@shrewd inlet
idk how to explain it
whatās that
multiple, like it can only give them the āstaffā role but if i wanna give them the āmemberā role it doesnāt do anything
it is
Any errors?
ah
^
nope
well the code seems completely fine to me
but I could be missing something so wait for someone else to hopefully respond with an answer
ahh I see
use a * operator before role arg
since its only taking north as the role
or just use id or mention
which probs doesnt exist
yes
Using ,role "north america" is also a solution
:lemonshake:
thanks!! i did that :)
thank you!!!!
alright cool
How do I add an environment variable using python ? ```py
os.environ["name"] = "value"
or is there some other method..
yes
I want to change Jishaku settings , and it uses env
that works
Alright ty
do you have a get_bank_data method?
possibly 
or
make open_account return account data and make new account data if the data doesnāt exist
somethings wrong with your syntax highlighting wtf
can you show that whole file? async and await arent highlighted which is weird
well you copied code but you didn't copy everything, and how would we know what get_bank_data is supposed to be?
Ok this is very general but can anyone point me into something to explain to me how restorecord bot works? Like how it gets the permission from users to make them rejoin a server
They use an Oauth2 scope that gives them permissions to make a user join a guild
Or at least I'm assuming so, as that's the only way to make a user join a guild
could u link me to an open source bot that uses the same stuff or a video?
No clue of any
https://discord.com/developers/docs/topics/oauth2 Refer to here
Integrate your service with Discord ā whether it's a bot or a game or whatever your wildest imagination can come up with.
what is @staticmethod for?
Basically a method for uninstantiated classes
Regular methods have self as the first parameter, there for needs to be called with an instantiated class
Staticmethods don't
You don't need it for a class that doesn't have a constructor
Either way if your class didn't have a constructor it would use the default one
!e ```py
class Foo:
pass
print(Foo)
print(Foo())
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | <class '__main__.Foo'>
002 | <__main__.Foo object at 0x7f143385d510>
still kinda dont get it
and wdym by uninstantiated classes
Refer back to my evaluated code
The first print shows an uninstantiated class
The second one is instantiated
what does that word mean?
If it's constructed or not basically
ah i see
Anyone know how to connect a bot to a voice channel the user is in?
I tried this
@bot.command()
async def joinvc(ctx):
channel = ctx.author.voice.channel
await channel.connect()
But it gives this error
Ignoring exception in command joinvc:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 27, in joinvc
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1277, in connect
voice = cls(client, self)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/voice_client.py", line 199, in __init__
raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
!e ```py
class A:
@staticmethod
def foo() -> None:
print("bar")
A.foo()
A().foo()
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
001 | bar
002 | bar
ahhh i see
install pynacl
Mkay
so what does the decorator do? exactly
simple. You don't need self, use staticmethod
ah i see
so it makes it static
Yep a static method
ahhh makes more sense thank you guys
now i have to add it to 1000functions 
im not joking btw*
my code has 1000functionsš š
Are you just using a class as a namespace?
wdym a class as a namespace?
you mean to organize it all?
Sure
yes i am
Like Class.foo() instead of foo()
im adding all of those functions to the class yes i am
That's gonna be a pain
yes
If your only using the class as a namespace I don't really see the point in that
i like it
Although sadly, python has no namespace per-say like C++
Idk, this seems pretty redundant for OOP here, functional programming will do just fine
š¤·āāļø
20minutes straight of doing ctrl v ctrl c for 1000functions lets go
is there any built in listener for "on_command_use" or something of that nature? looking to track what commands get used the most / who's using them and unsure how
on_command event
got it, thank you
why tho lol
discord.py can be used but it will break in some time if discord changes something ( for verified bots)
and yea disnake is one of the stable forks
;))
is it the same way to install packages ? on repl it
my firs ttime using it
you mean import them
yea š
yes
and did you made that?
yes
its from my code i am just trying it on repl it
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
⢠PEP 8 document
⢠Our PEP 8 song! :notes:
okay
whats this mean?
invalid syntax
hmm.
its not correct lol
you dont pip install in a file
you do it in the terminal
ah
i see
thanks!
hi
stackoverflow exists
how to use tthe bot?
all the errors:
no need to import embeds,member,color member again error handlers,taks and commands again,client,json again,schedule 2 times,time,dont do wildcards imports to follow pep8 no need to import weebhook and requestweebhookadapter,use asyncpraw,dont import ext commands 3 times,no need to import a function from random
oh :0
pardon?
its !
i got it
lol
It's eval
its used to evaluating code
evaluate?
It's used to run a Python code
!e
print("hi i evaluate code")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
hi i evaluate code
#bot-commands
Lol
good one
Nvm, he's doing something in there
Seems like he wanted to find that channel and go there
Ignore what okimii said, we took the wrong meaning before @spark plaza
no worries
oh my bad i thought he was moderating me
lol
Hllo
no need for channel
you can just do
await ctx.send()
show your command
nvm
not really but dont convert bet to an int
just tylehint it
!pep 484 read this
he's doing bet = int(bet) so doesn't matter. Anyways typehinting it will reduce one line
u could use .lower() ig
what does -> after function declaration do lol
saw something like this the other day
def a(b) -> int:
pass
return type
so would it force the function to return an int or?
!e py def fun() -> int: return "string" fun()
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
What's the error, if you don't mind me asking?
no, it's for the typechecker to see if the return type is the specified type or not
I would've thought that the problem is that you didn't use an f"" string or .format(), so it shouldn't show an error
alright
Try that, I feel like it should fix it. Maybe Python doesn't like the characters { and } in a basic string
From what I remember they're always highlighted differently from the string in VSCode, so there's some significance
Yeah, I thought so š
missing a colon
uhhh why....why....?
do ```python
f"Wrong Argument! It should be py {Heads/Tails} {Number}"
what...?
is heads a str?
he forgot to add f before the string
Yep
is heads/tails a str?
idk
or an int? cause you're basically dividing it
then what do you want to do lol
"{heads}/{tails}"
oh right lol
The f doesn't show up, it's just the correct syntax for string formatting
also it's useful for libraries for the users to know what the function they're using returns. For example this function returns str
and if it's a str you can't divide it
If you are using string formatting, heads and tails are variables
What would the value of them be..?
right.
So you can't just divide them
do they want it to be divided?
But in this case it's a bit confusing
what do they want
I don't think so, but I don't know
I don;'t know hahaha
For example if they try
!e ```python
print(f"Wrong Argument! It should be py {Heads/Tails} {Number}")
@bronze pilot :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'Heads' is not defined
yeah
I'd go for {heads}/{tails}
Oh I get what you mean
and it's saying it?
Try putting a backslash before the "special" characters? (;ike { and })
is heads an int?
no
It's a common feature in most programming languages, should work in Python
what do you want it to say?
worth a shot
give us an example
No dude, listen
we can't blind guess yet
what do you want it to say
No seriously, try ```python
await ctx.send('Wrong Argument! It should be py {Heads/Tails} {Number}')
oh, so remove the {}
If it works then it works, if it doesnt then i have another idea
why did you put \ before the {} when it isn't even an f string lol
it's not a special character without the f
Try re.escape(your_string) if that doesnt work
bro
yeah
im confused af
then why are you giving answers?
i think {Heads/Tails} and {Number} are just the arguments they are trying to tell the user to input (not sure this is confusing af)
I dont know what they're trying to get across
I'm confused about Number
Im confused about *
No no, I meant it as "everything" just a joke
Someone please come and help me in
ask
you can do await ctx.send("wrong argument! it should be py Heads/tails") but Im not sure about why you need the bet amount in there
well, they know what they betted
oh
then it should be await ctx.send('Wrong argument! It should be py {random.choice["heads", "tails"]} {bet}')
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Idk why it's a thing
is there any case where ctx.channel.send() is preferred over just ctx.send()?
await message.add_reaction("ā
")
await message.add_reaction("ā")
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji

full error
copy the ones from discord, I had this error before and it worked for me
watch
\ā
Ah you are using same ones
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\thosiba\PycharmProjects\main.py\main.py", line 244, in gamble
await message.add_reaction("?")
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\message.py", line 1223, in add_reaction
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\thosiba\PycharmProjects\main.py\main.py", line 28, in on_command_error
raise error
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\thosiba\Downloads\d-bots\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji
hmmmm
he is using the unicode emojis i think
iirc there is like an ID thing for emojis
It looks to be the same ones from discord
When I started with Discord bots I saw a tutorial saying put a backslash before any emoji and you can copy it like text
huh
what are the emoji ID things called again
Done that for the tick and cross emojis and it worked
wha
the ones that look like <1398479743121312112>
why infernum always shows up suddenly and dissapear again
that's unicode
he's a ghost behind the wires
emojiname:emojiID but that's for custom ones
\š¬
oh :sadge:
unicode or not, it worked for me
I'll go sleep now
what time there
I'm going to cause more trouble than not
that's custom emoji
Going away as well bye guys, happy new year when it comes
:sadge:
still 3 days lol or 4
Good afternoon ladies and gentleman.
m = await ctx.channel.fetch_message(some.message.id)
for r in m.reactions:
if r.emoji == "š":
await ctx.send([users.name for users in r.users])
TypeError: 'method' object is not iterable
It gave me this error. Someone help me to fix it.
@velvet tinsel Help me
and why sleep again
Iām tired ok
:l just straigh into prob
ok ||no, i won;t let you sleep||
Bruh I already said here.
Full error please
Here.
what's error :)
what is the error i mean
Also why make a for loop
Traceback (most recent call last):
File "C:\Users\LeeHaoMingDennis\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\LeeHaoMingDennis\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\LeeHaoMingDennis\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'method' object is not iterable
Then how bruh
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
Python acting up
This
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not iterable
can someone ask a not-hard question related to discord.py or disnake im bored
excluding HelloHello's
š¤¦āāļø
i said related to discord.py or disnake
if you don't know what disnake is, just an active fork of discord.py which is maintained since discord.py is no longer getting maintained
Help me
for š„zample
Wrong
can't, but which event are you using, on_raw_reaction_add or on_reaction_add
š
Then how?
What
# Handling report if gameid is not valid
@report.error
async def report_error(ctx, error):
if isinstance(error, KeyError):
...
How can I handle key errors from commands?
you got an error or something?
Command raised an exception: KeyError: 190
Thats when invoking the command
I know why its an error, but just want to do x when it happens
@velvet tinsel @maiden fable Um?
wait isinstance in discord.py not handle default errors in python
why not hi me ;-;
Isnt there a way with CommandInvokeError
there's an on_error event too
U need to use TextChannel.fetch_message
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
I used ctx.channel.fetch_message
Reaction.users is a method
by calling it
How do I flatten it
TypeError: object of type 'coroutine' has no len()
@visual island
How do I keep my bot online at all times?
Imagine using a database
;-;
No
Txt/json is the best
Bro what
then how
Try except are not used for discord errors
Someone in the replit server told me that
Nope
oo
Then heās stupid
ok
replit database kinda nice tbh
um what
ez to learn
ez to use
even dumb pepo like me know how to use
.
it's basically json, not a good db
Use a error handler
Ok
like this one
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f'Dont spam :/ try**{round(error.retry_after, 2)}** seconds')
else:
raise error
```?
This though
dont spoonfeed
...
No
that is me
nvm
im not spoonfeeding myself
head smack
They just copy and pasted the error handler
yeah that'd work
This though
nonono
NO wait
its in my code
Cool
but im facing issues
that'd be a global error handler
Like what
ya
if you only want it for your command, use @funcname.error
i wanna make different command to have different ways to tell u that u are on cd
Naw they can just use a global handler
wdym
Unless you want different responses for different errors xD
like if u are hunting in cd then it will tell
you hunted too much try in another blah blah sec
if u are fishing in cd then it will tell
you fished too much try in another blah blah sec
Then yeah do what @heavy folio said
!funcname.error
eh
Yeah
what is the command for the api
I donāt know
;-;
?
nothing
He wants a !d command
@hoary vale.error
what i do here
oh
wtf
it's the same
Bro
the func is the same
What donāt you get
BRUH
Itās simple
@ hunt
!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.
just change @bot.event to @hunt.error?
Yep
ok
With an @
Hunt 
!ot
Off-topic channel: #ot2-never-nesterās-nightmare
Please read our off-topic etiquette before participating in conversations.
Imagine hunting without Hunter

Hunting code without you is terrible
I miss you š©
Oh code hunting... Nvm
...
I wish you could be here more often so I can go to sleep
I do that only at night most of the times, so, uhhh
I'm going rn, cya
Rather than people pinging me at 1 AM
@velvet tinsel
NOOOOOOOOOOO-
!ot-names
Off-topic channels
There are three off-topic channels:
⢠#ot0-psvmās-eternal-disapproval
⢠#ot1-perplexing-regexing
⢠#ot2-never-nesterās-nightmare
The channel names change every night at midnight UTC and are often fun meta references to jokes or conversations that happened on the server.
See our off-topic etiquette page for more guidance on how the channels should be used.
seccd = round(name.get_cooldown_retry_after(ctx))
mincd = 0
hrcd = 0
rseccd = 0
rmincd = 0
if seccd > 59:
rseccd = seccd % 60
mincd = (seccd - rseccd) / 60
elif mincd > 59:
rmincd = mincd % 60
hrcd = (mincd - rmincd) / 60
if rseccd == 0 and rmincd == 0 and hrcd == 0:
res += f':white_check_mark: {name}\n'
else:
res += f':spinning_clock: {name}: **{hrcd}h {rmincd}m {rseccd}s**\n'
whats wrong here
How do i get the context of the first message in a channel?
!d discord.ext.commands.Bot.get_context
await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the invocation context from the message.
This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.
The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
fetching the first message in the channel would be a hard task
await new_channel.history(oldest_first=True, limit=1).flatten() could work
sure
just get that message object , and use get_context to get the context
thank you for the help
I need help setting up a code. I have the code finished, just not sure how to make it work. Can somebody help me?
AttributeError: 'HistoryIterator' object has no attribute 'content' sadge
help
run it
u wanna host the bot isit
RoWifi
u wanna make embed?
so theres not a way atm?
no I just wanna make a command like this
????
And some guy helped me make this code for that command
oo
what are u trying to ask
u already have the code
just paste that into ur bot's code
I did
and run it
do you have requests imported
help ;-;
groupId is not defined as well
Oh yeah- forgot that one let me do that rq
error?
and ctx should be cts
it is actually
its ctx bro
or cts ctx
the opposite
pip install requests
tfw when u just copy code without knowing what it does
just dont use requests
i still dun und what is wrong here
use aiohttp....
but its not working
wasn't directed towards u
ik but i did that sometimes when i get fed up
sad that it doesnt work
issue?
and code
AttributeError: 'HistoryIterator' object has no attribute 'content'
overwrites = {
ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True)
}
new_channel = await ctx.guild.create_text_channel(f"welcome-{ctx.author.name}", category=new_member_cat, overwrites=overwrites)
await new_channel.send(ctx.author.id)
await new_channel.send(message_struct)
first_message = new_channel.history(limit=1, oldest_first=True)
first_ctx = await bot.get_context(first_message)
print(first_ctx)```
Hm-
its a list uk
do y'all know any alternatives to restorecord
i forgor
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationās message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
I need a command that gives the user role he has in a roblox group.
Also, if possible, for it to change his nickname. Actually, to add (Rank) @amber beacon to his nickname!
Here is the current code I got.
groupID = 9247039
robloxCookie = ""
xsrf = ""
@bot.command()
async def promote(cts, user: int, role: int):
with requests.Session() as group:
# get xsrf, its needed.
group.cookies['.ROBLOSECURITY'] = robloxCookie
xsrff = group.post('https://friends.roblox.com/v1/users/1/request-friendship')
xsrf = xsrff.headers['x-csrf-token']
# Promote user!
url = f"https://groups.roblox.com/v1/groups/{groupId}/users/{user}"
group.headers["Content-Type"] = "application/json"
data = {"roleID": role}
res = group.post(url)
await ctx.send(res.json())
If you could help me, would be appreciated a lot.
Anybody? -_-
@bot.command(aliases=["wyr"])
@commands.guild_only()
async def wouldyourather(ctx):
async with aiohttp.ClientSession() as session:
request = await session.get("https://would-you-rather-api.abaanshanid.repl.co")
reqjson = request.json()
embed = disnake.Embed(
title="Would you rather...", description=reqjson["data"], color=0x7194FF
)
embed.set_footer("ID: " + reqjson["id"])
await ctx.reply(embed=embed)
this doesn't work and always says courotine obj not suscriptable
there's no full traceback since i also have a on_command_error event which shows it, i just got a enable tracemalloc
wait nvm i figured it out
!charinfo ā
\u2705 : WHITE HEAVY CHECK MARK - ā
its await request.json
!charinfo ā
\u274c : CROSS MARK - ā
@small igloo #bot-commands
i forgor sorry
how do I view my bots cached users/members
idk
yeah i eventually figured that out before u did
gr8
sounds kinda cocky
bot._connection._users
remove the invite , it has your token
oh yeah
ty
you can just provide the piece of code and the error here for people to help
no error
or if its too long use a pastebin
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.
but i am smart too
i had a back up
now i will have to spend
hours working on it
HUH
it worked but I had to make a new
i have 0 idea what u are talking about
um ok
I WILL sue replit's ceo
...
I will
he made my bot remove 10 commands
just do its f replit updating and package failed nuisance
that will surely go well
what kind of things should be stored of infractions, or is this enough? ```sql
CREATE TABLE IF NOT EXISTS infractions(
id serial PRIMARY KEY,
user integer,
apply time,
expire time,
active bool,
type text,
reason text,
)
oh maybe the actor
just use another editor then?
!ot-name
Off-topic channels
There are three off-topic channels:
⢠#ot0-psvmās-eternal-disapproval
⢠#ot1-perplexing-regexing
⢠#ot2-never-nesterās-nightmare
The channel names change every night at midnight UTC and are often fun meta references to jokes or conversations that happened on the server.
See our off-topic etiquette page for more guidance on how the channels should be used.
ĀÆ_(ć)_/ĀÆ
ĀÆ_(ć)_/ĀÆ
ĀÆ_(ć)_/ĀÆ
ĀÆ_(ć)_/ĀÆ
stop chaining
async def suggest(ctx, command, *, description):
': Suggest a command. Provide the command name and description'
embed = disnake.Embed(title='Command Suggestion', description=f'Suggested by: {ctx.author.mention}\nCommand Name: *{command}*', color=disnake.Color.green())
embed.add_field(name='Description', value=description)
channel = ctx.guild.get_channel(924998519432036393)
msg = await channel.send(embed=embed)
await msg.add_reaction('š')
await msg.add_reaction('š')```
Idk why this code aint working
Do share the suit when you do
Lmao
Care to define 'not working'...
And do you have an on message event
like embed isnt sending
Do u have an error handler?
it doesnt give an error
tbh i dont know how to debug
⨠print("It gets to here") āØ
just add print statements to see which lines gets run
Im guessing the command doesn't get invoked. See: https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
ok
async def suggest(ctx, command, *, description):
': Suggest a command. Provide the command name and description'
embed = discord.Embed(title='Command Suggestion', description=f'Suggested by: {ctx.author.mention}\nCommand Name: *{command}*', color=discord.Color.green())
embed.add_field(name='Description', value=description)
channel = ctx.guild.get_channel(924998519432036393)
msg = await channel.send(embed=embed)
await msg.add_reaction('š')
await msg.add_reaction('š')
await bot.process_commands(ctx)```
Like that?
do you have on_message event?
thats the all my code
yea, thats all the code for the command
^
@bot.event
async def on_message(message):``` something like that?...
do you such function?
...
do u have anything that resembles this
im talking about all of your code , not the command particular
just use ctrl+F , and search for on_message
now, how do you invoke the command
hm
like "!suggest" or what
yep
hm , do you have a on_command_error event
nope
logged in
i occured in c:\Users\rrfda\OneDrive\Desktop\sublime pg version\buttons.py
Task exception was never retrieved
future: <Task finished name='discord-ui-view-dispatch-e67a5c9c3fc4fd3e697bce3b94ce65e3' coro=<View._scheduled_task() done, defined at C:\Python39\lib\site-packages\discord\ui\view.py:346> exception=AttributeError("'Interaction' object has no attribute 'send_message'")>
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\discord\ui\view.py", line 355, in _scheduled_task
await item.callback(interaction)
File "c:\Users\rrfda\OneDrive\Desktop\sublime pg version\buttons.py", line 48, in callback
await self.ctx.message.delete()
File "C:\Python39\lib\site-packages\discord\message.py", line 1188, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "C:\Python39\lib\site-packages\discord\http.py", line 339, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
code when
await self.ctx.message.delete() what's context here?
Will my bot get rate-limited with this?
@commands.Cog.listener()
async def on_member_join(self,member):
stats_channel = member.guild.get_channel(921720659653054464)
count = len(member.guild.members)
await stats_channel.edit(name = f'Member Count : {count}')
@commands.Cog.listener()
async def on_member_remove(self,member):
stats_channel = member.guild.get_channel(921720659653054464)
count = len(member.guild.members)
await stats_channel.edit(name = f'Member Count : {count}')
depends on how popular your server is
probably , just dont edit the channel names as soon as the member joins the server , i'd run a loop which edits the channel name
but using tasks.loop seems better
It will be
use loop then
Ok
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
!src
logged in
i occured in c:\Users\rrfda\OneDrive\Desktop\sublime pg version\buttons.py
Task exception was never retrieved
future: <Task finished name='discord-ui-view-dispatch-d3d16ef88b75f4ea0620d4587e6a202c' coro=<View._scheduled_task() done, defined at C:\Python39\lib\site-packages\discord\ui\view.py:346> exception=AttributeError("'Interaction' object has no attribute 'send_message'")>
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\discord\ui\view.py", line 355, in _scheduled_task
await item.callback(interaction)
File "c:\Users\rrfda\OneDrive\Desktop\sublime pg version\buttons.py", line 48, in callback
await self.ctx.message.delete()
File "C:\Python39\lib\site-packages\discord\message.py", line 1188, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "C:\Python39\lib\site-packages\discord\http.py", line 339, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```
Do you know what is the shortest amount of time I can make the task.loop() so the bot doesn't get rate-limited?
a minute or two would be cool in my opinion
Ok thanks
update_data function?
You have 3 arguments
where is it
It required 2
read what dekriel said
Would this work?
@tasks.loop(minutes=2)
async def on_member_join(self,member):
stats_channel = member.guild.get_channel(921720659653054464)
count = len(member.guild.members)
await stats_channel.edit(name = f'Member Count : {count}')
@tasks.loop(minutes=2)
async def on_member_remove(self,member):
stats_channel = member.guild.get_channel(921720659653054464)
count = len(member.guild.members)
await stats_channel.edit(name = f'Member Count : {count}')
yeah youtube
bro why are you copying code without understanding
no, that's not how you use tasks.loop
oh
man i just realized using apis which use json are so easy with aiohttp
ghost ping , cool
indeed
there's even a would you rather API which does that, only has 119 questions tho
The idea is:
- Loop every 1 minute or so
- Get the guild
- Count the members
- Edit the channel
dont copy code, 1) you wont learn anything from it
2) the indents are broken 
3) json isnt a db
nice database bro 
logged in
i occured in c:\Users\rrfda\OneDrive\Desktop\sublime pg version\buttons.py
Task exception was never retrieved
future: <Task finished name='discord-ui-view-dispatch-d3d16ef88b75f4ea0620d4587e6a202c' coro=<View._scheduled_task() done, defined at C:\Python39\lib\site-packages\discord\ui\view.py:346> exception=AttributeError("'Interaction' object has no attribute 'send_message'")>
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\discord\ui\view.py", line 355, in _scheduled_task
await item.callback(interaction)
File "c:\Users\rrfda\OneDrive\Desktop\sublime pg version\buttons.py", line 48, in callback
await self.ctx.message.delete()
File "C:\Python39\lib\site-packages\discord\message.py", line 1188, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "C:\Python39\lib\site-packages\discord\http.py", line 339, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message```
But that's what I have done haven't I?
oh wait no
I haven't
what are you trying?
if you can't create a bot, you can't develop it, if you don't want to develop a bot, don't create it
code?
wait
I think you replied to the wrong person
just the delete button is having some issues
š
lmfao
yes wrong reply
its passed inside the class ```py
class Delete_button(Button):
"""
Some discord button that deletes the author and the bots message if everything goes smoothly
Arguments
ctx : discord.Context should be passed
class discord.ButtonStyle
or discord.ButtonStyle.danger, discord.ButtonStyle.gray
----
"""
def __init__(
self,
ctx: commands.Context,
style: Literal[discord.ButtonStyle.danger, discord.ButtonStyle.gray] = None,
) -> None:
self.ctx = ctx
self._style = style
super().__init__(
style=self._style or discord.ButtonStyle.danger,
emoji=f"{random.choice(Emojis.trash_emojis)}",
)
async def callback(self, interaction) -> Coroutine:
"""
A discord.ui.button callback function returns a coroutine
deletes the bot message and the authors message
-----
when the if statment fails
it sends to the user a random error_reply with a random "pepe" sad emoji
ephemeral=True so only the user can sees it'
"""
if interaction.user.id == self.ctx.author.id:
# checking if the author id meets the user interaction id
try:
await self.ctx.message.delete()
# deleting the author message
except AttributeError:
#most likely they used a slash-command, so there isnt a message to delete
pass
return await interaction.message.delete()
# and finally deleting the interaction message which is the bots message
return await interaction.response.send_message(
f"{random.choice(Replies.error_replies)} {random.choice(Emojis.pepe_sad_emojis)}",
ephemeral=True,
)```
the only thing which could be considered as spoonfeeding are examples, examples are a concept of implementation
I understood everything he said lol
i mean not understanding what the code does
Is it like this @visual island?
@tasks.loop(minutes=2)
async def serverstats(self,member):
while True:
stats_channel = member.guild.get_channel(921720659653054464)
count = len(member.guild.members)
await stats_channel.edit(name = f'Member Count : {count}')
await self.bot.loop.create_task(serverstats)
while True isnt needed
be honest, idk if you made those docstrings or copied it, im now a copy-code detective
oh ok
i made them lmao
cool cool
deadass
but thanks for the compliment
and to start a task use func.start()
Ok
@tasks.loop(minutes=2)
async def serverstats(self,member):
stats_channel = member.guild.get_channel(921720659653054464)
count = len(member.guild.members)
await stats_channel.edit(name = f'Member Count : {count}')
await func.start(serverstats)
also does this follow pep8 guildines on naming class variables conventions ?
also, don't put anything in the args except self

