#discord-bots
1 messages Β· Page 435 of 1
@stark python :white_check_mark: Your eval job has completed with return code 0.
hehhe
see, works wonders ahshaha
lol
python's like the USA lmao
you can do everything
I just started to learn C# and I'm feeling pretty closed in
c# claustrophobia
im starting university next month and im trying to learn some things and get used to this enviroment

C# is dictatorship
I'm gonna start calling people grandpa
sounds about right
delete_after work in ephemeral messages?
it's a kwarg in Messageable.send()... I don't think the message matters
why want
their
bot to ping and reply
them
dm me i ll give
What does the client function do in discord bots
it's not a function...
where are you writing that code im just wondering bc i want to make a bot
visual studio
i am not exactly sure but it is because of members intent being disabled
members intent?
I just copied the answer from FAQ and got my ID from dev mode
!d discord.ext.commands.Bot.get_user
get_user(id)```
Returns a user with the given ID.
but the method is at discord.Client class
is it in a command?
yes
then why use client
i think he is using AutoShardedBot
because I use async def handle(self, params, message, client):
Β―_(γ)_/Β―
it doesn't matter, consider enabling intents and using ctx.guild.get_member()
Actually I'm using Discord Bot Template
what does that have to do with anything
and why don't you have ctx there
you should consider enabling intents
is there a way to use it without client?
the client param?
can you show the part of code
async def handle(self, params, message, client):
#getting parameters from params
owner_id = *censored*
owner = client.get_user(owner_id)
msg = "a message"
msg_o = "some message to me"
await owner.send(msg_o)
yea
what is client
discord.Client object
why is it in the parameters of the command
How do i obtain the member count of my server? I've tried client.get_guild(id)
and then guild.member_count
how to make ban everyone command
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
!rule 10
:x: Invalid rule indices: 10
!rule 9
I require to execute owner = client.get_user(owner_id)
that still doesn't mean it should be in the parameters
and why are you using self?
are you using cogs?
what are cogs?
understood
you can replace self with ctx
delete the client parameter
and place a @client.command() decorator above your function
gives me error
in fact, actually i'm not working at one file, but one file each command
it's a way to break up your discord bot into parts
huh

this is how a command's built in cogs
#decorator that says this is a command
@commands.command()
async def test(self, ctx, **kwargs):
#here's your code
#you use self.client or self.bot, most likely bot, since it's made for commands
ok...
does anyone worked with this template? https://github.com/agubelu/discord-bot-template
wait da heq
this template separates main code from commands and events
so coding commands is very different but handy to code

π©
The template doesn't use cogs
but uses a predefined base
I never seen a worse way to make a Discord bot in my life.
exactly
use normal dpy...
what's dpy?
cogs
and I don't think it's a big deal
to have it in one file
they have docs on everything,
tutorials everywhere,
discord.gg/dpy has help channels
and this channel mainly supports discord.py-
and some discord-components stuff I think
Do you guys suggest the use of cogs? its just different files to categorize everything right?
they have benefits
a cog for moderation, a cog for embeds, a cog for role assignment?
you can reload them, for example
what does that do
don't gotta restart the whole bot
just a part of it
make an autodeploy on github
whenever you update it, the host deploys it
!reload commands
π₯
I don't have to go to my Raspberry PI and restart the whole bot since I can just use a command
so in my experience, they're pretty useful
if you don't need them, don't have to
Β―\_(γ)_/Β―
the RBI is only able to host a thing or does it host alot of stuff?
nice
just buy a desktop 
What is wrong?
wouldn't be enough
how do i place my bot in other servers?
no i dont have cogs i nned the code plus ow it works
have the owner to invite it?
oh right its on that site i was just throwing out a random question

i get Interaction Failed but the button works 
guild_id[id] = {"id" :id , "channel":channel}
file = json.dumps(guild_id)
with open ("id.json","w") as f:
f.write(file)
the code is correct right? but i got an error :l
nvm i got it
Someone? Please?
does anybody know the solution to this problem?
for word in f:
ValueError: I/O operation on closed file.
someone knows the script who change every 10s the bot status?
@client.command()
async def test(ctx):
msg = await ctx.send("[ ] 0% ")
await sleep(3)
await msg.edit("[===== ] 25%")
await sleep(3)
await msg.edit("[========== ] 50%")
await sleep(3)
await msg.edit("[=============== ] 75%")
await sleep(3)
await msg.edit("[====================] 100%")
await sleep(3)
await msg.edit("testing....")
await msg.edit("Done.",components = [Button(style=ButtonStyle.red , label="Delete")])
test = await client.wait_for("button_click",check= lambda i: i.component.label.startswith("Delete"))
await msg.delete()
await test.respond(content="deleted.")``` i want the only ctx.message.author who can use the button :-( idk how any help?
So i've been meaning to format my bots timestamp info like this for a while but i'm not sure how to do it. I had a look at a few guides but i'm still not exactly sure how it' done. I want to make it look like that for my member joined aaand account created timestamps
okay thanks
yw just search on google or ask someone
thanks anyway
does anybody know the solution to this problem?
for word in f:
ValueError: I/O operation on closed file.
u didnt open the file
The code:
with open("path/file", "r+") as f:
if message.content.startswith(message):
message.channel.send(f)
for word in t:
pyautogui.typewriter(word)
Pyautogui.press("enter")
Error:
for word in f:
ValueError: I/O operation on closed file.
just do r instead of r+
I'm getting global check failure in a command in a cog when testing on an alt, but I don't think I've implemented a global check anywhere. The cog doesn't have a check override. I have the on_command_error and on_message event outside of cogs though. Is there a function that might have accidentally added a global check?
do you have a bot.check somewhere?
nope
I do have a def bot_check in a different cog though
Nope same error
oh
bot_check is a method that adds a bot check same as the bot.check decorator. Which is a global check
ctx.guild.owner_id
what u tryna do?
I'm trying to open a file on command with a variable because when I put the open command the file I want to open opens no matter what and I want it to only open with a variable
with open( . . . ) is a context manager, that being said it closes the file after the block inside of the context manager is finished
Meaning the for-loop will have to be inside of the context manager as well
You have to enable the members intents
@pliant gulch is it neccesary to close the file after opening it?
Could slow down your bot, sometimes changes don't go into effect until file is closed, etc
Many reason to not want to leave open the file
I mean, just think about it? Why would you keep the file open if you aren't using it afterwards
true alright got it thanks
the opened file will take up memory
how do i set a default value to the member who called the command?
how do i get account connections( i didnt know the name of them i just googled it )
A bot does not have access to those
it's markdown
wdym
it's mark down syntax highlighting
so how do i do it
no put diff there
np
is this ur bot btw?
how do i remove a reaction for an on_raw_reaction_add
nope
show
and it didnt highlight it?
nope
lemme try one sec
um
it worked?
it didnt
oh wait mb
i didnt put the 3 backticks at the end
still no
diff\n - [] = optional argument
i have that
lemme see
there
diff\n- [] = optional argument
yep
thank youuu
np
Also one more question
so i have a snipe command that can do as many snipes as you want right?
mhm
how do i make it automatically delete the stored messages like every hour
so the bot doesnt lag
for each individual server
i have nothing in mind sorry
you can ask someone who's much more qualifed than me
@lusty swallow wrong ping sorry
how do i remove a reaction for on_raw_reaction_add
@bot.event
async def on_command_error(ctx, error):
embed=discord.Embed(title="Uh oh... :sweat_smile: ")
embed.add_field(name="It seems I've ran into a problem", value=error, inline=True)
await ctx.channel.send(embed=embed)
i want to make it so when they say like xjrf4jhgbjgjrn my bot doesnt respond but if they say a actaul command with a error, my bot tells them the error, how in the fuck do i-
How can I make the variable have different values on different servers?
add if isinstance(error,commands.MissingPermissions or something else):
Hey can someone help me with discord.py
I was wondering if I can use client events and commands in the same code?
nevermind
#help-carrot any one its about regex to get 4y or time in the for of year
and what are you trying to do?
which user?
does it have manage roles perms?
send the error
show the code
the full code 
:incoming_envelope: :ok_hand: applied mute to @cedar smelt until <t:1630375259:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 117 newlines in 10s).
lol
if i had to guess you're getting hierarchied
!paste use our paste site please @cedar smelt
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.pydis.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.
!unmute 760501716662878240
:incoming_envelope: :ok_hand: pardoned infraction mute for @cedar smelt.
to avoid spam
anti raid ig
We check for spam. Some people will send a lot of newlines to troll and we check for it to prevent it
Im making a whois command and i'm having an issue where instead of just naming the roles it gives the role id's and puts in a bunch of other charcters
the code is
@commands.command()
async def whois(self, ctx, member: discord.Member=None):
member = member or ctx.message.author
current_time = datetime.today().strftime("%I:%M %p")
embed=discord.Embed(title="Whois Command | Epic Bot",
description=f"Returns with the information of a user or yourself.\n\n**Username**\n`{member.name}`\n\n**Roles**{member.roles}",
color=0xff0000)
embed.set_author(name=f'{member}', icon_url=f'{member.avatar_url}')
embed.set_footer(text=f"Epic Bot | Discord bot | Today at {current_time}", icon_url='https://cdn.discordapp.com/embed/avatars/1.png')
embed.set_thumbnail(url=f'{member.avatar_url}')
await ctx.send(embed = embed)
I'm just trying to make it so it lists the roles instead of this result
My solution:
@commands.command()
async def whois(self, ctx, member : discord.Member):
roles = [role.mention for role in member.roles[1:]]
await ctx.send(discord.Embed(description = f"Roles: {' '.join(roles)}"))
How make the bot to add roles for a specific command?
Alright thank you
I need to learn how to use stuff like that cause it's pretty useful in removing unwanted characters
Hey.
Any discord.py users out there?
feel free to check my status
we're always looking for contributors and pull requests are more than welcome.
our goal is to keep a maintainable future for discord bot development in python now that discord.py is out of the picture
Advertising is punishable I think
From a performance stand point... would it make sense to have a single 'main' on message received' and then split out into Cogs or have a different on message in each Cog. I feel like it would be the former so you aren't repeatably checking the message over and over
g=random.randint(1000,16777215)
@bot.command()
async def c(ctx):
role=discord.utils.get(ctx.guild.roles, name='colour')
user=ctx.message.author
await user.add_roles(role)
while True:
print('change colour...')
await role.edit(name='colour', colour=discord.Colour(g))
print('changed')
time.sleep(0.5)
why sometime work sometime it not work ???
Not sure 100% But from how I see it, the former (main) on_message would have a bunch of if/elifs statements I'm assuming which would take a while depending on the number to traverse. On the other hand commands.Cog.listener makes a listener which is ran on a message create event in this case. Meaning instead of traversing through all the if/elif statements in the main on_message it fires directly to whatever you wanted (that being said you would need an if statement to make sure its the case you want)
To make the listener part clearer, it adds an extra event listener which is dispatched along with any other same event you registered
so mostly... the former may be better performance wise but at the cost of added latency?
@bot.event
async def on_message(message: discord.Message) -> None:
if case1:
pass
elif case2:
pass
#vs multple listeners
@bot.listen()
async def on_message(message: discord.Message) -> None:
if case1:
pass
@bot.listen("on_message")
async def case2_on_message(message: discord.Message) -> None:
if case2:
pass
Idk if I said was very clear so heres an example
I hope you can see what I am trying to say
thanks π
You could probably timeit to really see which ones is faster as I said earlier my thought isn't 100%
have you actually installed the discord.py package?
idk how
i installed python
what IDE are you using?
visual studio code
pyhton 3.9.7 @feral cargo
what do you guys think will happen to discord.py because danny retired?
what category would snipe command come under?
fun, mod, info, bot, misc
which one
fun
In that case run pip install discord.py
A proper open source fork or new wrapper will take its place
jack helped me fix it
Current watching a few forks and a new wrapper and seeing where it's going
since i dont have a env file what line should i use to run my token?
Install discord.py
.
client.run("") correct?
Yes
Ok
Is there a function to get a users discriminator like there is to get a name?
!d discord.User.discriminator
The userβs discriminator. This is given when the username has conflicts.
ty
Np
The error speaks for itself, you have two commands with the name or alias avatar.
Hey @visual island, can u share the code where u trigger the typing but it types indefinitely in my DM?
Thanks
it's fixed actually
U were using typing() and not trigger_typing()?
the function it ran has a wait_for function which stops the context manager, so i create it as a taskcreate_task(func(*args, **kwargs))
yeah
async with args[0].typing():
discord/abc.py lines 1455 to 1468
"""Returns a context manager that allows you to type for an indefinite period of time.
This is useful for denoting long computations in your bot.
.. note::
This is both a regular context manager and an async context manager.
This means that both `β`βwith`β`β and `β`βasync with`β`β work with this.
Example Usage: ::
async with channel.typing():
# simulate something heavy
await asyncio.sleep(10)```
So this is what u were doing
See the example
That wait for was sort of something heavy
wait_for is not heavy actually, it is waiting for an event to be dispatched, if it not dispatched then the context manager wont exit
Yea, that makes it sort of heavy, just like asyncio.sleep(10)
PIL is very heavy
If the event never dispatches, then it won't run the code after it
That is some next level stuff 
that's why i used asyncio.loop.create_task
lol
Haha cool
wait, im having exam
Sure
btw, what are you going to do with it?
Eh, nvm if it worked. I was seeing if it was a bug in the library itself cz many people were facing the problem a few weeks back. Could be it's fixed
Hi!
yeah, and what else would be added in the github repo?
Uhh there are many features getting added to the repo. We have a release date, and the first version of library with context commands, slash commands and Buttons should release before 10 September (hopefully within this week)
context commands?
User, Message Commands
ctx
https://github.com/EQUENOS/disnake/blob/master/discord/ui/button.py i thought button was finished
Indeed
But we haven't tested those much tbh
The version which will be released would be the beta version for now
dpy have that?
In 2.0, yes
But I don't really know if they are released
Since EQ is developing those himself
EQ's skill is equivalent with Danny ic
Yups
He has been deving since 2018
He also says that, Danny changed his life too
BTW
If u want to start moving to disnake, the basic commands system is usable
did anyone create a server setup bot?
As long as u don't use the newer features like context, slash commands and the Buttons, u r fine
The easiest way to transfer would be
import disnake as discord
Ezz
does the button.py still uses the v2 implementation, or dislash's implementation?
as i think v2 is quite stable already
EQ is working hard to make sure discord.py's original syntax is preserved and can be used. It also uses views, so yea. It uses the v2 implementation
can i open a PR of something?
but idk what should i add/change tbh
Sure. We are open to PRs. But if it is related to the Discord API, then u will have to talk to EQ, cz he's the one who codes the API side of the wrapper. Others filter out bugs and adds custom features
If you want, I can provide u an invite to the support server and u can talk with EQ there
what
disnake?
isn't that my lib?
!pypi disnake
A python wrapper for Discord API forked from discord.py.
h u h
......
Oh
w h a t
π
I think he made it after mine lmao what
mine was last updated about 6 hours before his, not sure tho
did he rename it to disnake? I think it used to be dsc
Frankly, unless your library is profoundly good or way far ahead of all other efforts, I think it won't get adopted just on grounds of it using camel case.
I think camel case enthusiasts suffer in Python cause even if their code uses it, the majority of the ecosystem and the standard library don't, so they just end up with inconsistent styles which is arguably worse
Forks already started killing Library Internals 
Pycord released third "Bot" class which can be used for slash commands. Basically proved the older and newer system are totally incompatible
help
word in message.content, message is the discord.Message object which is not iterable
? me
Yes
can anyone explain me why we save bot tokens in .env file and not in .txt?
where in vscode or in replit
i did not understand
replit
but i use heroku tho
its there already for environments
currently, i have directly put my token in the main boy file (bot is only in 1 server)
What you didn't understand? message is the instance of discord.Message class which can't be iterated. message.content returns the content string which is iterable, so use that.
so i should write discord.Message
in simple words
You can save them in any file and that does not really matter unless it's some public host kinda thing like replit

Read that again
understood


?
English Please
bhai means brother
I know...
:3
u changed the name from dpy to disnake in the commit history
sure
with?
wdym
like a command where you can have spaces for the guild name?
ctx,*,arg
lol
Breh, I didn't... It was decided as the new name and I just changed the README file to depict those changes...
okay ig
ima just leave python
this has happened to me like 5 times already
I made my own wrapper cause my friends needed one and they begged me to use python cause they need help
Aw, that's sad. Well, u can always choose a new name!
@crystal kestrel I have just suggested that cz people don't use camel case in Python.. They use snake case. So people won't be comfortable with using your wrapper...
@maiden fable if i give my bot a emoji unicode that is not present in server, so will it react with that emoji
await re.add_reaction(":z_wrong:")
No
how can i do that
ok is it like this
:z_wrong:
No
i wrote something else
Add a ``` before the emoji and it will send the whole emoji with ID
can u gimme a example
:z_wrong:

\
Just add a \
i did like that but it erased that
Weird

how do i make my bot send a message without me using prefix like suppose i send hello i want it to reply hi
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | async def test
003 | ^
004 | SyntaxError: invalid syntax
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | async def test:
003 | ^
004 | SyntaxError: invalid syntax
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | ctx.send(
003 | ^
004 | IndentationError: expected an indented block
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botβs own messages and private messages are sent through this event. This can lead cases of βrecursionβ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
#bot-commands
sorry
@maiden fable how to get emoji from other server
?
the method i used before didnt work
!d discord.PartialEmoji this is what is returned
class discord.PartialEmoji```
Represents a βpartialβ emoji.
This model will be given in two scenarios:
β’ βRawβ data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")
β’ Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Message.reactions "discord.Message.reactions")...
Read the docs, from where u can get those
wth is this
Emoji but Partial
ok
From a guild the bot can't see
everything going over my mind
From the guild the bot isn't the member of
ok but how a class can help ?
Good morning guys
403 Forbidden (error code: 50013): Missing Permissions how?
like for kick
PLS HELP
:(
If the user is not in the guild or you are trying to kick the owner.
@client.command()
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
#sets value in json to guild id upon the bot joining the guild
@client.event
async def on_guild_join(guild):
#loads json file to dictionary
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("result.json", "w") as f:
json.dump(guildInfo, f)
#allows server members to set channel for welcome messages to send to
@client.command()
async def welcomeMessage(ctx):
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets channel to send message to as the channel the command was sent to
with open("result.json", "w") as f:
json.dump(guildInfo, f)
``` this is my code i want the server name to be stored as well what do i do?
i am the owner
Need more info then.
i am trying to kick a member
it is good for server id
understandable but its for a small bot and ijust need the server id and the channel id to send the welcome messages to
so i need a way to store server names as well
Uh..? No..?
panda yelp
You'd only need to store the id
yea but as the discord client login has been closed down i need to know the server names as well or is it against TOS?
just to see which servers my bot is in thats all
Are you making a self bot?
its in 20 servers now

That has always been against ToS
i have no way to get id so i had to use this code i just need a way for server names as well
It was meant to automate small things but people abused it.
i know like read messages π
But i'm not helping with self-botting.
nah i just need a way to get the server names as well
or is it against TOS?
wait
Yes.
@client.command()
async def changeprefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to: {prefix}')
i just want to know the servers my bot is in and store it in a json like a database nvm leave
aha
then it will be stored it the file with the prefix the server uses
r+ mode exists.
i m a beginner.
'''python
@client.command()
async def add(ctx, *nums):
operation = " + ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
@client.command()
async def sub(ctx, *nums):
operation = " - ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
@client.command()
async def multiply(ctx, *nums):
operation = " * ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
@client.command()
async def divide(ctx, *nums):
operation = " / ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
how do u format it?
async def add(ctx, *nums):
operation = " + ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
@client.command()
async def sub(ctx, *nums):
operation = " - ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
@client.command()
async def multiply(ctx, *nums):
operation = " * ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')
@client.command()
async def divide(ctx, *nums):
operation = " / ".join(nums)
await ctx.send(f'{operation} = {eval(operation)}')```
cool rite?
async def changeprefix(ctx, prefix):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes
prefixes[str(ctx.guild.id)] = prefix
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
await ctx.send(f'Prefix changed to: {prefix}')```
prefix changer
This is mine ```py
@commands.command()
@commands.is_owner()
async def db_prefix_debug(self, ctx, prefix):
await self.bot.con.execute("UPDATE guilds SET guild_prefix = $1 WHERE guild_id = $2", prefix, ctx.guild.id)
await ctx.send('Updated!')
You can put as much decorators on there as you want, just for a command to succeed it will all need to be True. So if @commands.has_any_roles() is the moderator role and it also has is_owner() it would be the owner of the bot that has the moderator role.
Yes.
You can make your custom decorator for that!
The docs are pretty good on this one -> https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#checks
async def on_ready():
guilds = client.guilds
data = {}
for guild in guilds:
data[guild.id] = []
for name in guild.name:
data[guild.id].append(guild.name)
with open("new.json", "w") as file:
json.dump(data, file)``` this is my code but on the json file im getting like some 20 outputs of the same server names help
How do i make my bot detect role permission change? + the one who changed it
!d discord.on_guild_role_update
discord.on_guild_role_update(before, after)```
Called when a [`Role`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Role "discord.Role") is changed guild-wide.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
The who can be found in the audit log
Never done that so can't really provide help with that but the docs do provide some info.
thank you
What's the difference between a news thread an a public text channel thread?
Not really a reason i think, they probably named it like that since that channel is news related. It is also a bit of a special channel like rules and events. News channels also have their own category -> discord.ChannelType.news
Hope that covers your question a bit, i could look into it more but i'm guessing it's mainly this.
@bot.command(aliases=['Poll'])
async def poll(ctx,question : str):
bot_msg = await ctx.send(f"**{ctx.author.name}#{ctx.author.discriminator}** asks: `{question}`")
await bot_msg.add_reaction(":GreenTick:")
await bot_msg.add_reaction(":RedCross:")
when i use the command it only detects the first word after the command but not the whole sentence. how do i make it detect the whole sentnce
Use *
I want to do help='SOMETHING' but i am using aliases
I need more context.
I'm not working with discord.py, that was more of a question about the API. I was wondering why threads created in a news channel have their own separate type π€·
async def poll(ctx, *,question : str):
like that?

async def poll(ctx, *question : str):
...whereas #rules is just a text channel
@client.command(pass_content = True)
async def leave(ctx):
if (ctx.voice_client):
await ctx.guild.voice_client.disconnect()
await ctx.send('I left the voice channel')
ok
Hmm i will try and see if i can find some more info.
it turns out like that :p
wait nvm i fixed it ty! @cloud dawn
Since it makes it into a tuple
ty lol
I can't really find anything about it on the internet. So i guess it's just naming what i did found out however is that they are going to change threads alot imo -> https://support.discord.com/hc/en-us/articles/4403205878423-Threads-FAQ#h_01FDGC4JW2D665Y230KPKWQZPN
Code?
k
@bot.command()
async def react(ctx, chat:discord.Message.id, emoji:discord.Emoji):
if chat is not None:
if emoji is not None:
message = chat
await message.add_reaction(emoji)
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Emoji which you want to React")
else:
await ctx.send(f":exclamation: {ctx.author.mention} Please Specify the Message on which you Want to React")
this is code :/
async def on_guild_join(guild):
#loads json file to dictionary
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("result.json", "w") as f:
json.dump(guildInfo, f)``` error-raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type TextChannel is not JSON serializable
panda help
typehint is invalid
pandaaa
?? :/
is chat passed as a message id?
yes
i want to use the command like this
guild.id needs to be in a string
>react msgid emoji :/
Ahhh i get it you can't typehint a message object, you will need to fetch it.
:/ i am not understanding :/
#loads json file to dictionary
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo str(guild.id) = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("result.json", "w") as f:
json.dump(guildInfo, f)``` will this work?
how to solve that :/
No it still needs to be indexed
oh oki
how to add reactions?
Don't typehint it and fetch it.
Logging is handy in most of the applications
typehint it as an int or str.
hmm should i use it as str?
I find that logging gives excessive information.
how to add emoji as reactions?
Not only for a discord bot
Best use case since if it is not and int since someone did not read the commands manual it would still crash.
:/ k
How to add an exception handler for NotFound? I tried both isinstance(commands.NotFound, error) and isinstance(discord.NotFound, error), but none of them worked
async def on_guild_join(guild):
#loads json file to dictionary
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo str[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("result.json", "w") as f:
json.dump(guildInfo, f)``` syntax error
HTTP exception raised when message bot tries to operate with gets deleted
HOW DO U ADD A EMOJI REACTION
await msg.add_reaction()
It is mostly used to easily find errors and runtime problems.
msg?
Message object
ctx?
Set your logging level to debug when you are running your bot and you'll see
So who knows how to handle NotFound
My PC starts lagging as I open the debug logs 
ctx is commands.Context and not discord.Message, however it has message attribute which is right format you need
Dpy heavily uses logging, literally all the data it receive is logged
Debug logs have so much info that you can't even find the error
@lament mesa bro yelp
@tawdry perch
Eh lemme explain
Code blocks on mobile is not readable
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.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.
HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji
@client.event
async def on_guild_join(guild):
#loads json file to dictionary
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo str[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("result.json", "w") as f:
json.dump(guildInfo, f)
Like I said you need to use a string as key since you are using json
This is HTTPException and not NotFound
I will try to raise it rq
can you tell what should i exactly change in my code i tried doing it already'
Str(guild.id) inside [[
NotFound: 404 Not Found (error code: 10008): Unknown Message
hey can anyone help me on wats wrong here ?
I'm on my phone π
done still synatx error
You didn't import choice?
Choice isn't defined..?
What?
Str?
please tell how to get emoji id
The emojiβs ID.
What the hell is guildInfo str[guild.id] = ...
Expecting value: line 1 column 24 (char 23) this is the error now
Maybe you meant guildInfo[str(guild.id)] = ...?
yea done
!traceback
Please provide a full traceback to your exception in order for us to identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / 0
ZeroDivisionError: integer division or modulo by zero
The best way to read your traceback is bottom to top.
β’ Identify the exception raised (e.g. ZeroDivisionError)
β’ Make note of the line number, and navigate there in your program.
β’ Try to understand why the error occurred.
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
okay but know i have another error
Define ch?
Lol
async def on_guild_join(guild):
#loads json file to dictionary
with open("result.json", "r") as f:
guildInfo = json.load(f)
guildInfo [str(guild.id)] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("result.json", "w") as f:
json.dump(guildInfo, f)
```Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 172, in on_guild_join
guildInfo = json.load(f)
File "/usr/lib/python3.8/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/usr/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 24 (char 23)
Like what are you choosing from lol
Please learn Python with a simpler project, dpy requires some basic knowledge dude 
Wrong format you are trying to dump I believe
hmmm yea i thought i could do it
It's like you think you can drive truck without knowing what is sterring.
Learning with projects is efficient and fun, but first go with a simpler one.
So does anyone know how to handle this
NotFound: 404 Not Found (error code: 10008): Unknown Message
Whatever operation you're trying to do, message can't be found by the api
hmm yea like is there like a minor error that is fixable ? or just wholw code is bad @slate swan
How to handle this in error handler I mean
Can you dump a text_channel object inside an .json?
Like isinstance(what, error)
No, only its ID
guys
Everything is fixable, it's just a minor error. But still you'll experience more difficulty as you go deep with dpy
i think you can beacuse i got this on stackflow and apparently it worked for many
please tell the id of π
Default emojis don't have any id
It is unicode emoji, it doesn't have id
You don't need its id for any cases
hmm peace would be helpful if i know what mistake i did this once
So right now we are fixing someone else's code that you want to implement?
If you want to add reaction of it, just do
.add_reaction('π')```
I can tell but it's of no use. 
I just use postgre so my json experience is -5%
no mine is this which works ```@client.event
async def on_ready():
guilds = client.guilds
data = {}
for guild in guilds:
data[guild.id] = []
data[guild.id].append(guild.name)
with open("new.json", "w") as file:
json.dump(data, file)``` i need a one which gives me the first text channel
so i need somthing to figure it out
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji```
Why you're even appending the name into a list, there will always be one name for one guild
just map the id with name
shoul i inport emojis?
oh oki ill try that
I am not sure, but all formats json can store seem to be int, real, str, date(time) and maybe bytes
@client.command()
async def Poll(ctx , *, question):
bot_msg = await ctx.send(f"**{ctx.author.name}#{ctx.author.discriminator}** asks: `{question}`")
await bot_msg.add_reaction(':π:')
await bot_msg.add_reaction(":π:")```
And yeah None as well
You don't need to put : in emoji name
Can json store int's as values? I know keys has to str
I LOVE YOU:)
Import re
Yeah keys have to be str I think
??
will it allow me to use commands as well as messege.content.startswith('$kick)
How to handle this in error handler?
NotFound: 404 Not Found (error code: 10008): Unknown Message
I tried both isinstance(commands.NotFound, error) and isinstance(discord.NotFound, error) but none of them worked, what class should I use to handle it
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3.10/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3.10/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3.10/library/stdtypes.html#types-union).
You shouldn't process commands like this
help @slate swan
then
Correct usage of isinstance ^
In code I used them correctly, I confused here
This has to be the most cursed tutorial ever made
@bot.command()
Please stop pinging randomly
also what is with that emoji you're pinging me to?
How do I avoid getting rate limited?
Don't send many requests?
sorry
Don't spam the API and don't use repl.it
Heroku is almost equally bad
Dont use heroku π€¦ββοΈ

then anyother free thing
Use VPS 
?
Or just use localhost or else an vps
not free
Will you please stop pinging me from anywhere randomly with that emoji?
Nothing in life is free
u r frnds are free
???
Not being rude but it's better to block if you don't stop
k srry
bro
my frnd
Air is free. yet
Dude
I said STOP PINGING please!
can i trigger a command of my bot using an api of a website?
i dont think so
You can do a lot but you cannot invoke commands
Yes, you can listen to the response and invoke the command
Btw
Wait api? Are you sending them response your bot is acting like a server
what do you mean by spam the API? Hmmm
it means spamming and not getting responses due to many requests
correct my frnd @slate swan
umh I haven't done anything yet
Don't ```py
while True:
await channel.delete() # and stuff
then its fine
im looking for ideas
imagine pinging
no but ^
lol
pls no
sad
I don't think repl.it is that bad if your only making a bot as a hobby

π
You don't want your hobby bot to be rate limited for a few hours?
!d asyncio.loop.run_in_executor
awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.
The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3.10/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.
Example:
wait
I make bots for a hobby and I don't recommend it 
I don't even make bots and still don't recommend it 
PIL Will always be sync
I've been using replit for 4 months now and my bot hasn't been rate limited before only once
no but you can run it in an asynchronous executor
Why? I don't see enough reasons imo
^^
It's your luck. I once tried hosting a bot to experience it myself and got 4 times rate limited in 2 weeks 
Eh
Shared IP and bad hardware I'd recommend heroku more than repl.it since heroku actually is decent for 1/3 servers
you dont?
Not to brag but my bot only has 500 lines so no
I just make them to fill my github repos and pass time. After dpy got discontinued, I archived all the repos and now finding some another project 
hello im new
Why does it matter how many lines it has?
Doesn't matter
:/
Hi new I'm panda
hello im ryuk
anyway
how do i use this
Use what? Dpy?
i see but why don't you make your own wrapper for that
python, how do i start
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I have my exams in about 2 months and it's my final year of school, so maybe later Β―_(γ)_/Β―
ohh thanks
wait whattt
the heck
Just fork dpy and implement slash commands and done
ah, goodluck then
Thanks 
don't use asyncio.run
its incompatible with running loops
loop.run_until_complete
or yea that
Pycord already murdered all the internals and created a third bot class discord.Bot to use slash commands lol
since im new how should i start and what is this
!d asyncio.loop.run_until_complete
loop.run_until_complete(future)```
Run until the *future* (an instance of [`Future`](https://docs.python.org/3.10/library/asyncio-future.html#asyncio.Future "asyncio.Future")) has completed.
If the argument is a [coroutine object](https://docs.python.org/3.10/library/asyncio-task.html#coroutine) it is implicitly scheduled to run as a [`asyncio.Task`](https://docs.python.org/3.10/library/asyncio-task.html#asyncio.Task "asyncio.Task").
Return the Futureβs result or raise its exception.
Click on it..? Uuuhhh
lol
no no which one π€¦ββοΈ
Don't click on 3rd one please 
helphh
ok....
help
There is more than just these 4 these are more advanced tutorials
I never checked out pydis resources but you can search realpython.com for basics of python
oh thx
im looking for simple ones since i just started
π helphh me
https://realpython.com/tutorials/basics/ Here you go, just go through them in the order
You add an reaction to an message object not and bot instance
thanks!
so how do i do it
tell me pls
this?
you are using client , when ur bot name is bot
?
wait can a 13 y/o use this
:/
age doesnt matter
i'm 14 
oh
wtf
um, ghost ping?
I ignored that with people after 2 months of helping...
Imo, age does matter.
How do I check if the user's reaction is emoji based on the emoji I chose?
yea im confused asf
i suggest you use bot and also its await add_reaction(emoji)
and also the emjo should be named like this !SwagHappy
You timed out responding, also idk how discord_slash work but looks like you took more than 3 secs to respond
to get it you would have to do it like this \
and send it
thats why you shouldnt ignore anyone trying to help 
@slate swan
elif isinstance(error, discord.NotFound) or isinstance(error, discord.errors.NotFound):``` doesn't catch the exception I need
What class to put to there
hm , i have a class ping me after 45 mins if u didnt get help
Wdym unwrap?
how to name it like this
It works with all other exceptions besides this one
Slash commands are fine, bad but not much, yeah their implementation is much different than usual
i showed it .. \
A lot of people do this because of bad YouTube tutorials even big coding YouTubers make this mistake like freecodecamp
?but how did u show it in this form????
i just read the docs
tutorials kinda suck
https://vcokltfre.dev best tutorial and docs
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
In 2022 you are going to be forced to use slash commands so I hope you like it more in the future π
do this back slash \ then emoji after it , please listen and send it
no way ?
They will disallow any bot to read user messages
This won't happen
That is why Danny stopped with discord.py lol
Yes, it's like 3 seconds to respond, and if you did, next 15 mins to use followup.
It's a bit complicated but have a look at this gist https://gist.github.com/AkshuAgarwal/bc7d45bcecd5d29de4d6d7904e8b8bd8. I made it according to discord.py but it might still clear most of the doubts
where did u get that info ? 
@slate swan
Reading user messages is not only for commands yk
In Danny's gist (discord.py dev)
remove emoji and the comma
they make it a priviledge intents
just like reaction and members
ohk
then how did danny know that ?
He's not even a developer lol, he's a medical professional 
We'll see...
@slate swan
@slate swan so how to fix this
elif isinstance(error, discord.NotFound) or isinstance(error, discord.errors.NotFound):```
I don't know anything more. Maybe someone else might help
opened it?
Ok
I guess I gotta go to help channels...
I can't really help anyone rn since I'm on my phone lmao
on the on_message funcion or define message in your function and add this
await message.add_reaction(':Heart~2:')
await message.add_reaction(':heartEyes~1:')```
It's irritating to see 1 blocked message everywhere on the screen 
error = getattr(error, "original", error)
CommandInvokeError needs to be unwrapped
unknow emoji????
just, put it below async def on_command_error

discord.NotFound is also wrapped inside commandinvokeerror? 
ohk
its
@command_name.error```
@slate swan
No I mean like
elif isinstance(getattr(error, 'original', error), discord.NotFound):```?
the emoji is not in the server or the id is not true
1 sec
It is local error handler, I am using global one
i was trying in dms
lol
so i should try in server
just add it in a embed and maybe use a img idk how other bots do it , ask the google 
alright 
shieeeeeeet
@visual island
elif isinstance(getattr(error, 'original', error), discord.errors.NotFound):``` didn't work, I am sure I did it wrong, could you show an example?
@slate swan it works on me not on my bot lol
just make a check that checks if its a bot and if its a bot it would react with that

@bot.event
async def on_command_error(ctx, error):
error = getattr(error, 'original', error)
# do stuff
Will it affect other handlers?
no
Even custom exceptions?
unless they have any original attr, no
In this tutorial, we will learn about the Python getattr() method with the help of examples.
if isinstance(error, commands.CommandInvokeError):
error = error.original
This should also work
That's why I don't believe in forks 


