#discord-bots
1 messages · Page 723 of 1
hello
Yeah nah, I absolutely despise that
I tried some hosting services that were made for discord bots, like ploxhost or what not
They use the same system, pterodactyl panel
and its absolutely terrible, like they have a console but you can't run commands init, it is just for logs, then you have hardcoded startup command and you can't run any shell commands using a programming language as it results to a permissions error
Maybe it's the hosting service but pterodactyl in itself is awful to use
I will use GCP/ aws, its good
this might've been changed though, since that link no longer works (at least for me)

yeah that link was taken down/moved, and the tos was probably revised
Eh, well you still can't trust em really
@client.command(pass_context = True)
@commands.has_permissions(Administrator =True)
async def mute(ctx, member: discord.Member):
role = discord.utils.get(member.server.roles, name='Muted')
await ctx.add_roles(member, role)
embed=discord.Embed(title="User Muted!", description="**{0}** was muted by **{1}**!".format(member, ctx.message.author), color=0xff00f6)
await ctx.send(embed=embed)
else:
embed=discord.Embed(title="Permission Denied.", description="You don't have permission to use this command.", color=0xff00f6)
await ctx.send(embed=embed)
This is mute command what is wrong?
it's an indentation error, your editor / IDE will point you do that
Also the code is wrong
which code is right then?
You don't need pass_context
and Context class doesn't have a method as add_roles
ye how to update then bruh
It's a method of the Member class
you have to use utils i think
!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.
you probably don't have an outdated one, check your version first
The super outdated one would not have the commands framework
print(discord.__version.__)
^^that's how you check, and yeah it's prob not that old
mhm
File "bot.py", line 267, in <module>
@bot.event()
TypeError: event() missing 1 required positional argument: 'coro'```
no () in bot.event
oh ok
lool
it's like that with most free hosts
or they are bad, or they take your ip
there's no really 'free'
i hate the pterodactyl dashboard
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "bot.py", line 279, in give
await add_points(users, member, amount)
TypeError: add_points() missing 1 required positional argument: 'pts'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/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: TypeError: add_points() missing 1 required positional argument: 'pts'```
show your code
your missing an argument where u call the function
and yeah, it says it in the error
bruh
but me dont understend heh
is the person using it an admin? nvm
its administrator, not capitalized
oh typo
just for test bruh
might want to learn some more python first before working on a bot
trying to be nice but yeah
this is not a beginner project
learn at least the basics
You definitely need have strong python knowledge before using discord.py, it's not beginner friendly
you should 
Also the error raises an Argument Error, which basically means that you didn't pass something to argument in the function you made
He probably doesn’t even know what that is 
-_-
!e
def func(a, b):
return a + b
print(func(1, 2)) # passing values to the arguments of the function named "func"
@untold token :white_check_mark: Your eval job has completed with return code 0.
3
Now
!resources || go through this
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
ah ok
!e
def func(a, b):
return a + b
print(func(1)) # passing values to the arguments of the function named "func", but I only passed to only a single argument
@untold token :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: func() missing 1 required positional argument: 'b'
cuz is my first time of
Me on phone too
I would have destroyed you
I am on phone too lol
well…uhh…
that's the reason you should learn python properly first
you can always come back to this later after getting some knowledge, however long that takes
Yep
I learnt the basics first
at first I was a bit of an idiot but then something weird happened and I started learning hype 
brush
brush
Well you need to have good knowledge of asynchronous programming
I-
don't know how async works
I passed an argument, not a kwarg when I should have been using a kwarg 💀
Mf go learn python
"we use async def for bot commands , because it should be done like that"
ok
exactly
You should learn it
amazing
and you await them when calling.
well done 
yes
you need to know when to await and when not to await, awaitables
Lol
What iş the best library for mobile app
Do you know why you have to do that?
this is discord bots
💀

yes
Are you süre?
I'm quite sure
wrong channel bud (unless you mean mobile discord app)
Shhhh
It’s discord.py 
oh mb
He doesn’t know what he’s talking about
no yeah, it's dpy
No, discord.py is an API wrapper that wraps around discord API and it's written in python, it has nothing to do with build mobile apps, you should go on #python-discussion to ask your doubts as this is the wrong channel
SHHH
No

he doesn’t know what he’s talking about
👌
Ovv sorry
Don't provide wrong help to people who are beginners, even it's for trolling purposes
it’s for mobile apps 
you ruined our fun
¯\_(ツ)_/¯
idk
~~its related to the current running loop and making sure when to yeild the return , without awaiting it it would just return you the method ~~

Uhhh
you can correct me if i am wrong.... thats what i knew about it.
after 10 years of experience with coding, do you become Caeden
probably
heyo, looking for a way to get error line in dpy (in code), outside of dpy this works:
try:
raise NotImplementedError("Not implemented")
except Exception as e:
exception_type, exception_object, exception_traceback = sys.exc_info()
filename = exception_traceback.tb_frame.f_code.co_filename
line_number = exception_traceback.tb_lineno
print("Exception type: ", exception_type)
print("File name: ", filename)
print("Line number: ", line_number)
but when using dpy, says tb_frame is none, is there a way to get error line number in dpy?
Ofcourse example is using try except - while in dpy I’m using error handler function
;-; yes but I can’t get the line the error occured on from trace back - only the description of error
How do I delete the command the person did
Let’s just say I did !help that it just deletes the !help
ctx.message.delete()
😐
Use on_command if you want it for all commands
but I still admire you ♥️
Ok
❤️
wat
ye, i guess your right. . .
this was the best traceback i can get, which again doesnt show the actual cog file nor the origin of the error. . .
trace = []
tb = error.__traceback__
while tb is not None:
trace.append({
"filename": tb.tb_frame.f_code.co_filename,
"name": tb.tb_frame.f_code.co_name,
"lineno": tb.tb_lineno
})
tb = tb.tb_next
print(str({
'type': type(error).__name__,
'message': str(error),
'trace': trace
}))
ask in #python-discussion
@cloud dawn if "@brisk portal" in message.content: ctx.message.delete() await message.channel.send(" please do not menion me thanks")
thx!
dms are closed?
what if theyre open?
It should work then
ctx.message.delete()
await message.channel.send(" please do not menion me thanks")```
I’m getting error lol
I think Ik why tho I want someone to do it
whats the error
you cant DM someone if you dont have any mutual servers with them
Well you don't have CTX in on_message
you will have to DM before banning
thats what i did
look
@bot.command(aliass=['k'])
@commands.has_permissions(kick_members=True)
async def kick(ctx,member : discord.Member,*,reason=None):
if member == ctx.author:
em2 = discord.Embed(description=f"**you** cannot `kick` yourself", colour=discord.Colour.red())
await ctx.send(embed=em2)
else:
em = discord.Embed(description=f"**{member}** has been `kicked` for **{reason}**", colour=discord.Colour.green())
await ctx.send(embed=em)
await ctx.guild.kick(discord.Object(id = member.id))```
its member.send
oh yeah
anyone can build bot?
ye everyone can
discord api is free to use so yeah
can someone help me with flask socketio?
ok , what about interest to develop or build bot have free well reactions
its ded
after can, interest, time
anyone have time?
i have no idea what you're talking about tbh
they are asking for help ig
with what
await message.channel.send(f"{message.author.mention} please do not menion me thanks")``` I wanna delete command on use someone help
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
discord.abc.Messageable.send
returns the Message object you send @slate swan
also that wont work if the bot has a nickname
Ok
It’s when someone pings me it deleted message
then it wont work if you have a nickname
how do i fix it
Code?
!e 1()
@sullen shoal :x: Your eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'int' object is not callable
check for both <@id> and <@!id>
@bot.command(aliass=['k'])
@commands.has_permissions(kick_members=True)
async def kick(ctx,member : discord.Member,*,reason=None):
if member == ctx.author:
em2 = discord.Embed(description=f"**you** cannot `kick` yourself", colour=discord.Colour.red())
await ctx.send(embed=em2)
else:
em = discord.Embed(description=f"**{member}** has been `kicked` for **{reason}**", colour=discord.Colour.green())
em3 = discord.Embed(description=f"**you** have been `kicked` for **{reason}**", colour=0())
await ctx.send(embed=em)
await member.send(embed=em3)
await ctx.guild.kick(discord.Object(id = member.id))```
any bot programmer want give me his time? and his knowledge ?
their**
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
what youre looking for are freelancing sites
no
im not look for freelancing sites
0()
Then what are you looking for
colour.red()?
do i remove the ()) where it says 0
@acoustic marsh what happened
If you want to have someone to teach you to code use freelancing sites
Damn they left
yes
dont call int objects
!e 0()
@sullen shoal :x: Your eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'int' object is not callable
@bot.command() #BALANCE COMMAND
async def bal(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
souls_amt = users[str(user.id)]["souls"]
em = discord.Embed(title = f"{ctx.author.name}'s balance",color = discord.Color.green())
em.add_field(name = "Souls", value = souls_amt)
await ctx.reply(embed = em)
async def open_account(user):
users = await get_bank_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["souls"] = 0
with open("mainbank.json", "w") as f:
users = json.dump(users, f)
return True
async def get_bank_data():
with open("mainbank.json", "r") as f:
users = json.load(f)
return users
@bot.command() #WORK COMMAND
@commands.cooldown(1, 30, commands.BucketType.user)
async def hunt(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
souls = random.randrange(11)
await ctx.reply(f"You went for a hunt and hunted {souls} souls!")
em = discord.Embed(title = f"Hunting!", color = discord.Color.red())
users[str(user.id)]["souls"] += souls
with open("mainbank.json", "w") as f:
json.dump(users, f)
What's wrong with my code? It gives me errors when I try to use it
Anyone?
show the traceback
wait
Ignoring exception in command bal:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\user\Documents\GitHub\ghostbot\main.py", line 18, in bal
await open_account(ctx.author)
File "c:\Users\user\Documents\GitHub\ghostbot\main.py", line 30, in open_account
users = await get_bank_data()
File "c:\Users\user\Documents\GitHub\ghostbot\main.py", line 45, in get_bank_data
users = json.load(f)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json_init_.py", line 293, in load
return loads(fp.read(),
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\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 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\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: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
would've helped if you were using an actual database for a job that is an actual database supposed to store
guess you could hope for someone else to waste their time
you used json as a database
thats what smart ppl do
and you are stuck with an error you will not have to care about if you use an actual database
i imported json to store the balances in a .json file
Using json as a database isn't smart
json is not a db
ye ik
Json isn't a database and if you use it as one, you will deal with more problems than good
Uh? what? Json isn't a database, remote or not
If you want a database that us similar to structure of json, use mongoDB
i saw it from a tutorial and I thought that if I changed just the variable it would work the same but it didnt
Or if you want relational database, use postgresql or even sqlite
Is this from swastik?
i mean
i dont remember
json is better than a nosql db which is remote
its been a while since I saw it
u can use json if u know how to handle concurrency issues
yes i searched it and it seems i have seen the video
Or literally just save yourself the trouble and don’t do that.
This error means that your json file is empty
i thought that the bot writes on the .json file when the command is triggered
Why would you even want to use something as something when it is not meant to be that thing
parsing and loading json takes time. as your bot will be used by more users the time will increase and one day you will reach the point where it will take ages to get the data
Json isn't better than any NoSQL db
I understood something from that
"w" = writes on the file
"r" = reads the file
and it was that in the code
Yeah that's correct
But if you are reading from an empty json file, you will receive that error
so the bot is supposed to write on the file by using this:
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["souls"] = 0
its on the open_account function
You have an empty json file? Right?
yea
Did you add {} in that?
No
Write {} in your json file, that way when you are writing into the json file, you won't get the error.
i will but last time I left it blank and the bot wrote it by itself
Ah hm
i might did it but not remember but i am sure that i didnt
so you are sure you didn't add it
Lol
another guy wasting their time for shitty code
sorry i guess
help
i am trying to make timeout commands and this shows p
It isn't your fault really, although you should learn proper databases
and use them make your stuff
rather than json
I am still learning discordpy
Cannot find git
Type git in console
You need to install git
....?
Ye
the path is correct tho
Well git isn't recognized
Install git
git is a command line tool, which is basically a version control system

bot isnt disconnecting from vc for some reason-
code
@commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
Get any errors
nope
!d discord.ext.commands.Context.voice_client
property voice_client: Optional[VoiceProtocol]```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
!d discord.VoiceProtocol.disconnect
await disconnect(*, force)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
An abstract method called when the client terminates the connection.
See [`cleanup()`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol.cleanup "discord.VoiceProtocol.cleanup").
@slate swan it's an abstract method (nvm)
There's no reason that would happen. The more likely scenario is that the users leaked the token themselves
is there anything wrong with the code?
what to do?
discord.Member not _
is there a way to fetch all the dms that someone sent to the bot
for dm in user.dms
something like that?
replace the name by replace_with?
idk, you'd have to log all the message history i think
member: discord.Member
^^change it to this
so i cant get anything from here on back, only from here forward if i started logging?
and idk if this is just me, but you should prob read the id as an int and fetch the member
yeah i think
hm.. alr
tried not working....
No
Well yea, that's a possibility but i didn't really asked the details so I can't really comment anymore, sorry
It's not valid to say that a hosting company is bad because someone leaked their token with them
Well yea, but I just told him what the other person whose token got leaked said. Nevertheless, I better not continue/comment
Still everyone is able to view the env file
not with repli
Anyways I gtg sleep, have a good day/night everyone!
gn
nvm
yo how do you edit fields in a embed message after its been sent
show your command decorator
he's definitely trolling lmao
.
Their nickname makes me believe they aren't
Imagine not using f strings
me too
Imagine not knowing how to use f strings
Is there any replit alternative
pydroid
nah windows
By alternative, do you mean alternative IDE, or alternative online IDE?
Also, not really the channel for that
But i cannot keep it always on
Online ide
vscode
you can use vscode text editor online :0
I mean, that dosen't let you run stuff
May i have understand, you wanna a alternative ide to keep your projects online?
Well, the only two I can think of is pythonanywhere, and one I have only a little experience with, codingrooms
Says you
Pythonanywhere is so bad
i have the solution, a sec
Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
🚨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables
Along the way, you will learn to use Repl.it's built-in database and cr...
Bro that's replit
.
oh, my bad
I thought he didn't know about this method of to keep the project online through the replit
replit is still bad for hosting
I use it on small projects and I never had a big problems.
mostly shared ips
is what makes replit bad
and how slow it is
i get it
¯_(ツ)_/¯
actually, replit is better for hosting stuff like sites. but replit isnt built for hosting discord bots.
i dont consider replit to be a terrible host, its just bad at hosting discord bots, as thats not what its intended to do.
replit isn’t even for hosting. It’s an online ide. It’s only meant to be used for writing code and testing. Nothing more.
I think you might be referring to heroku??? Maybe.
That’s more built for web stuff
now that i think about it, you're right.
either way. replit isnt for hosting discord bots, or as you said, hosting in general
using dpy 2.0, view.wait() doesn't work for dropdown menus - any alternative? im trying to reference the response from the dropdown in my main command
Quite a contradictory statement but I agree
hey i have question
do i can run 20 discord bots using 1 code and 20 config files
and each config file have token
i dont think that works
like if you are using cogs or something
im not sure if there is a limit on how many configs can use a cog
i dont think that works
idk there is a guy telling me it works but im saying no it doesnt work
then try it, it wouldnt take long
Yes you can.
pls help me i have wrote like almost 500 lines of discord.py bot's code and now i want to use cogs. how can i use cogs? I literally don't know anything about cogs. Pls help
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
what is @commands.guild_only()?
What do you think it does?
It’s just a decorator that makes the command it’s associated with a command that can only be used in a guild.
k
Hence guild_only
No
i am not using cogs
You can just add an argument and set the default value as none, then you can use conditionals to set the value of the added argument
do async def (self, ctx, member: discord.Member)
pull_from_db = member or ctx.author
pull_from_db is either member if passed or author
this is optimal
Oh yeah, pull_from_db.id
Add an argument user that has a default value None, then do user_id: int = user.id or ctx.author.id
To get id
user=None
Just like assigning a variable
so, you want to just fetch a users profile?
Rename arg to member if It’ s discord.Member and then do member = member or ctx.author
i don't understand
You should do
user = arg or ctx.author
user_id = user.id
Dont define user_id
Also if It’ s discord.Member it should probably be named member and not user so It’ s not confused with discord.User
class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Read this, It’ s rly handy
Click the link
You create a subclass of discord.View
And then you can do inter.send(view=YourSubclassOfView)
With discord or website
From discord api
Tf how
Replit has shared ip so of someones bot there gets ratelimited urs will too
It’s not bc I just copy and pasted code to new file and it works
It has shared ip
There’s why I never Use repl only for uptime
Wdym
I was lazy ok
🤔
Hows ur api wrapper @pliant gulch
?
It's doing fine
Not much development rn I might end up refactoring the codebase
I might use it for a bot

If I get any will to make another bot
If you do print(function()) it will print what function returns
Yea…
So if i do ctx.send(ball) (ball is my function it should send whatever is in the function right?
Im sorry, idk what you meant 😂
You have to call it
Lol i should explain it better
With ()
Dw
so ctx.send((ball))
ctx.send(ball())
But what I see from ur code, ball is a list
for checking if someone had permissions to kick, would it be this?
@commands.has_permissions(kick_members=True)
I think yea
That means they can only complete that command if they have that permission
Turns out the bot didn't have a high enough role
oh lol
Happens a lot
Are you trying to print a random value from this list?
Yes
8 ball command
Use random.choice(list)
Ok.
Also ball list should probably be named choices or answers or something
And put the list inside the function
Read on random.choice()
Yea i did try to name it 8ball but it glitched and gave me a syntax error
Ok thank you
You can't name it 8ball because it has a number at the start
That make’s sense
If you really wanted to name it 8ball you could just put an underscore before the 8 and that would be close enough
But choices is also a good name choice
is this how you would mention a interaction author
interaction.author.mention
!d discord.Interaction.user
The user or member that sent the interaction.
Yea thats a good point
how does user not have an attribute discrimator
Because it's discriminator, not discrimator.
!d discord.User.discriminator
The user’s discriminator. This is given when the username has conflicts.
fun spelling mistakes
hey! im looking for an affordable solution to hosting a bot! there are loads of options but its quite hard to tell which is better. does anyone have any thoughts / advice?
under $5 / month
iv heard of galaxygate and vultr but idk how they compare..
I haven't heard of those 😭
digital ocean
its lowest plan is 5$ a month
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
ye
it kinda depends where you live aswell
Most of these services are global, they should have servers in your region
true
is a radio command ageinst tos too?
Does {ctx.guild.boost_level} exist? Because I've a serverinfo command and I want to see the Server boosts
Like the count of
Or level
!d discord.Guild.premium_tier
The premium tier for this guild. Corresponds to “Nitro Server” in the official UI. The number goes from 0 to 3 inclusive.
ty
hi
Is there anyway that there is a command which shows what u are listening to right now
any way*
From spotify i assume?
Ye
if isinstance(member.activity, discord.Spotify):
print(member.activity.title)
*user can have multiple activities.
Guys I am trying to write an if statement to check if the embed has no fields in it, how would I go about this? I have this so far
if msg.embeds[0].fields is discord.Embed.Empty:
I am pretty sure it is
if msg.embeds in msg.content:
does anyone know how to save user input to a .txt file using discord.py?
how i make bot for discord
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
In this video, we go over how to setup a discord bot in python using discord.py v1.0.1 (rewrite).
If you have any suggestions for future videos, leave it in the comments below.
GITHUB: https://github.com/Rapptz/discord.py
DOCUMENTATION: https://discordpy.readthedocs.io/en/latest/
OFFICIAL DISCORD.PY SERVER: https://discord.gg/r3sSKJJ
JOIN MY ...
use this stuff
any idea of how to make a bot work in threads?
Shouldn’t watch yt videos for discord.py
They’re pretty bad
working on a music bot,
any pointers to what i should use for queuing songs?
i would like the ability to go back to previous songs, so i wasnt so sure about using queues,
but at the same time, wasnt sure how id check if something was added to an array when empty. . . (or max index reached)
Is bot.process_commands(message) the same as client.process_commands(message)
If i use client not bot
I tried it before and it didnt work I probably did something wrong
Well discord.Client doesn’t have commands
No
Yes it’s the same
depends what you call bot = to
either client or bot or anything works
Ok
could call it James if you wanted
Ugh no
That's like the worst
Code:
@bot.command()
async def purge(message, amount):
if not message.author.guild_permissions.administrator:
await message.channel.send('You do not have the `ADMINISTRATOR` permission in order to continue this operation!')
return
for i in message.channel.history(limit=amount):
try:
await i.delete()
except Exception as e:
print(f'[ERR] -> {e}')
Full Traceback:
Traceback (most recent call last):
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\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: TypeError: 'HistoryIterator' object is not iterable
https://paste.pythondiscord.com/kuhicimaco.py
⏫ main.py
https://paste.pythondiscord.com/dopubisifi.py
⏫ my_emote.py
local variable 'my_emote' defined in enclosing scope on line 8 referenced before assignment
help
line 593 main.py
is it possible to get a part of the code using eval
not sure
also is there a method which i can get command info, e.g. command name, help, aliases and other stuff
!d discord.abc.Messageable.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...
!customhelp
Custom help commands in discord.py
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
@slate swan doesnt it need to be async
^^^
!d disnake.ext.commands.Command.aliases
The list of aliases the command can be invoked under.
:/
@client.event
async def on_message(message,ctx):
if message.content.startswith("joe?"):
await ctx.send("hehehee")
await client.process_commands(message)
Does anyone know why my bot isn’t responding to “joe”
Or any other commands event tho i did the await client.process
yeah thanks!
not that
like everything in a dict
How do I get the total number of commands in a bot?
class disnake.ext.commands.Command(*args, **kwargs)```
A class that implements the protocol for a bot text command.
These are not created manually, instead they are created via the decorator or functional interface.
can someone help this
:/
nvm i got it
This is a shit tutorial, please dont follow it
:/
Me who learnt from seeing someone’s embed going to where it says title and changed it and called it my own embed
Wouldn’t recommend learning like that but i did
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.
This is a much better one
What error is it throwing
{Guest, Member, HonoraryMember, VIP, Moderator, Administrator, Organizer} ;-;
But why a dict
hi, very confused here. can someone explain why my bot use both . and ? as prefix for the commands when it is set to .. What I mean is that the bot answers when I do the commands with both dot/. and question mark/?.
here is how I set up the prefix, no idea why the bot answers to both when it is not supposed to do it
Bot = commands.Bot(command_prefix='.', case_insensitive=True, intents=intents)
Anyone know what the problem is with this code?
@client.event
async def on_message(ctx,message):
if 'fuck' in message.content:
await ctx.send("no")
await ctx.message.delete()
Its not giving any error
Got some more code? Or did you have ? as a previous prefix?
u should make the delete thing first
on_message doesn't take ctx
u are deleting the msg u are sending :/
But ctx.send does
No ..?
Well yeah I did use ? as prefix before but changed it, it seems to somehow still be there and answers to both now
Because the message im deleting is f*ck
What? You don't have ctx in an on_message event period. lol
Maby you got 2 bots running check task manager.
But then ctx.send isnt defined?
Yes indeed
Okay, didnt think of that. I will check it rn
define it :/
Thats what i did
@client.event
async def on_message(message):
if 'fuck' in message.content:
await message.channel.send("no")
await message.delete()
Jeez u were right, I should have thought about that, thanks anyway
Np, good luck
why is nobody helping this :/
Ive added “await client.process_commands(message)” to the end of my on_message code but it still isnt letting my other commands work
@cloud dawn when they see im typing 
elif messages[0] >= 100:
if any([bool(role) for role in member.roles if role in (Guest, Member, HonoraryMember, VIP, Moderator, Administrator, Organizer)]):
Reward = f"{1000 - messages[0]} messages away from becoming a Member." if role == Guest else "No further rewards to unlock"
await member.remove_roles(Visitor)
await member.add_roles(Guest)
Oop didnt mean to ping sorry
Could you show it?
We can choose the people we help. I chose not to help you because it is very unreadable.
ImportError: cannot import name 'Random' from partially initialized module 'random' (most likely due to a circular import) (/home/fazeexotic224/ZeroOne/cogs/random.py)
Some code?
its a import error
I know
@client.event
async def on_message(message):
if 'fuck' in message.content:
await message.channel.send("no")
await message.delete()
await client.process_commands(message)
import json
import os
import random
import sys
import aiohttp
import disnake
from disnake.ext import commands
from disnake.ext.commands import Context
import platform
from helpers import checks
if not os.path.isfile("config.json"):
sys.exit("'config.json' not found! Please add it and try again.")
else:
with open("config.json") as file:
config = json.load(file)
@commands.command(
name="randomfact",
description="Get a random fact."
)
@checks.not_blacklisted()
async def randomfact(self, context: Context):
"""
Get a random fact.
"""
# This will prevent your bot from stopping everything when doing a web request - see: https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-make-a-web-request
async with aiohttp.ClientSession() as session:
async with session.get("https://uselessfacts.jsph.pl/random.json?language=en") as request:
if request.status == 200:
data = await request.json()
embed = disnake.Embed(
description=data["text"],
color=0xD75BF4
)
else:
embed = disnake.Embed(
title="Error!",
description="There is something wrong with the API, please try again later",
color=0xE02B2B
)
await context.send(embed=embed)
@commands.command()
@checks.not_blacklisted()
async def info(self, ctx):
embed = disnake.Embed(title="", description="**[TwoZero](no self promo)**\n\nTwoZero-Statistics")
embed.add_field(name="OS", value=platform.system())
await ctx.send(embed = embed)
def setup(bot):
bot.add_cog(Fun(bot))
ok :/
my whole cog
Has to not be indented.
!global a small tip.
When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.
Instead of writing
def update_score():
global score, roll
score = score + roll
update_score()
do this instead
def update_score(score, roll):
return score + roll
score = update_score(score, roll)
For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.
@cloud dawn
i wanna make a list of variable in a function
cuz there are used quite often but idw to call them everytime cuz there is tons of them
should i use dictionary?
random is only imported at the top right?
wym
Wait let me ask the cavalry
yea py import random
Honestly i have no idea what you are trying to do.
You can just use the emoji's from the server and fetch them with the api instead of doing so much manual labor.
@cloud dawn
Most people are offline rn :/
:/
Your process_commands call is inside of the if statement, thus would only process commands when the if statement is True. Unindent the process_commands call by one level
Or 2 levels since you seem to be indenting everything by 2?
Told him that too 😅
Uh
But Andy any idea about the circular import?
I mean, seems like its a 2 space indent, so this is just the standard 4 message indent

maybe he has a file in the same root directory called random.py
Well you can also have just 1
Either or
As long as it is consistent.
And the circular import is probably because they have a file named random.py
You mean how many spaces ive put before my main code?
I said it first 
Yeah i was thinking that too
Just un-indent your process_commands call by 4 spaces
What do you recommend as the best slash addon to discord.py?
@client.command(pass_context=True)
async def unbanall(ctx):
guild = ctx.message.guild
for member in list(client.get_all_members()):
try:
await guild.unban(member)
print ("User " + member.name + " has been unbanned")
except:
pass
print ("Action completed: UnBan all")``` no error code what so ever
it just doesnt unban anyone
i would use a autoclicker but i have 441 ppl banned in my server
so this is the faster way
iterate through guild.bans()
!d discord.Guild.bans
await bans()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves all the users that are banned from the guild as a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`BanEntry`](https://discordpy.readthedocs.io/en/master/api.html#discord.BanEntry "discord.BanEntry").
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.
i dont understand
Help me...
What does this means???
And the token... I don't care. It's a test bot
Yep...
could you send me the end of the error code?
Would it be easy to create a discord bot dashboard for your desired bot?
ratelimited, cloudfare blocked your access
you on replit?
probably would be difficult, idrk tho ask some pros here
someone please help, am trying to make my bot welcome people but no matter how much i corrrect its not working.
import discord
from json import load
from pathlib import Path
from datetime import datetime
with Path("config.json").open() as f:
config = load(f)
channel_id = config["channel_id"]
token = config["token"]
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print("Everything is set to go!!!")
@client.event
async def on_message_join(member):
channel = client.get_channel(channel_id)
embed = discord.Embed(title=f"weclcome {member.name}", description=f"thanks for joining {member.guild.name}!", colour=0xf1c40f, timestamp=datetime.utcnow())
embed.set_thumbnail(url=member.avatar_url)
embed.set_image(str ="https://cdn140.picsart.com/286390297028201.png")
embed.set_footer(text="we would be glad if you show more love to us~", icon_url= str("https://cdn.discordapp.com/emojis/754736642761424986.png"))
await channel.send(embed=embed)
client.run(token)
you mean on_member_join
using this time converter
time_regex = re.compile(r"(\d{1,5}(?:[.,]?\d{1,5})?)([smhd])")
time_dict = {"h":3600, "s":1, "m":60, "d":86400}
class TimeConverter(commands.Converter):
async def convert(self, ctx, argument):
matches = time_regex.findall(argument.lower())
time = 0
for v, k in matches:
try:
time += time_dict[k]*float(v)
except KeyError:
raise commands.BadArgument("{} is an invalid time-key! h/m/s/d are valid!".format(k))
except ValueError:
raise commands.BadArgument("{} is not a number!".format(v))
return time```
how would i convert an arg where the argument is `s` `m` `h` `d` (second minute hour day) to retrieve a timestamp so i can have something like this
Would make a datetime.datetime object, then make a datetime.timedelta object with seconds minutes, etc then add the two objects together resulting in a new datetime.datetime, you'd then convert that into epoch time and use that for the timestamp
Well not the entire thing is a string
("UPDATE parties SET activity_points = ? WHERE user_id = ?", (hmm?, 491289245974003722))
globals are bad at time , try using bot vars instead
you can have something like ```py
bot = commands.Bot(....
bot.my_emote = {'emote1':'theemote'}
#when u need it :
bot.my_emote['emote1']```
it wouldn't be dead easy, but it wouldn't be too much of a challenge assuming you have web dev experience
ImportError: cannot import name 'Random' from partially initialized module 'random' (most likely due to a circular import) (/home/fazeexotic224/ZeroOne/cogs/random.py)
what are you even importing Random ?
also , its an inbuilt python library, really bad to name another file as random
Yea. Replit Hacker Plan :)
is there any way to remove your bot from servers you don’t have bot permissions in?
pls help cus my bot keeps getting random welcome messages
Can someone tell me what’s wrong with my code i cant work out how many indents i need in my else: its saying its a syntax error
@rickroll.event
@commands.is_owner()
else:
async def on_message(message):
if 'prick' in message.content:
await message.channel.send("no")
await message.delete()
await rickroll.process_commands(message)
I can't
It's supposed to be "@bot.event"
Unless ofc you reassigned it
Oh okay
Its something to do with my else:
that else is completely out of place
I think the indent is wrong
If i put it with no indents it says syntax error if i add any indents then it says unexpected indent
Why is there an else there in the first place?
There’s also no reason for @commands.is_owner() to be there either since its not a command, its an event
Because its a no swearing code i want it so because im owner (@commands.is_owner) it will ignore me because i am the string above else:
else: (if your not the owner) it will delete the word
True
Yeah you wrote it completely wrong then
Im new to this part of python sorry 😅
It's okay lol
We all start somewhere
Ofc ofc
Lol
I started with discord.py myself so ive been almost exactly where you are 
I started from stealing my friends embed code going to where it said title and changing it thats how i learnt to make a embed
Self-taught
Yes me too, not the best place to start at all but hey, it worked out lmao
vscode doesnt exist?
Yep, thats basically all it is
For hosting
..
I use vsc to
use a vps
But can't host my bot
.
so I bought a hacker plan
flask doesnt exist?
It's against ToS
bruh
Flask is against tos?
yo i need help
no
how do i get the guild id from a server that my bot is in
It means hosting a bot in replit for free.
i am not in the server and idk why it’s there
..
Its giving me a syntax error
You need a function
The check needs to be in the function
please help, there’s random welcome messages in my server
for guild in bot.guilds: print(guild.id)
for guild in bot.guilds:
print ("Guild Name: {} | Guild Id: {}".format(guild.name, guild.id)
You can host your bot in replit and flask. But it against the ToS
Ohhh i am so dumb 😂i need to learn to read my code haha
you need to specify more details about it
ty
no problem
.format() 
yep
true
it's way better
f-str is better
go cry
um no it's not but sure
you make codes look weird
...
dont bother trying to make him understand because he won't
it didn’t print 😭
Maybe try
@bot.event
async def on_ready():
...
guys is it possible to make a video streaming discord bot in python
thx
im planning to make one but idk if its possible
no prob
ig that’s a short concise answer, though slightly disappointing
because it isn't inside a function/event.
I already did everything for him
Discord's API = 💩
i have a koala command and it sends pictures of random koalas but when i added the embed, it gave me this error can someone help?
@commands.command(help='This command shows you a picture of a koala')
async def koala(self, ctx):
async with aiohttp.ClientSession() as session:
requests = await session.get('https://some-random-api.ml/img/koala')
dogjson = await request.json()
request2 = await session.get('https://some-random-api.ml/facts/koala')
factjson = await request2.json()
embed = discord.Embed(title="Koala", color=discord.Color.purple())
embed.set_image(url=dogjson['link'])
await ctx.send(embed=embed)
imagine thinking format is better than f strings
you still need help with on_ready events
fr lmao
guess hes in 2.0 or sm
im trying to make a "Any" button which randomizes choices (role objects), if the role is in author.roles: it'll choose again, else: it'll pass (so it doesnt random.choice() again
here's the thing, im not sure what to use, a while loop or?
requests = await session.get(...)
dogjson = request.json()
?
did u forget a s after t
please
I answered u
I also use
"Drugs are Yummy %s " %(Something)
^
it didnt ping me
send the code, i dont like reading
here's the thing, im not sure what to use, a while loop or?
send the already used code
bruh?
i already said i dont know what to use and your asking me to send the code, genius
because I always turn off pings while replying
but did u even read what I said now?
yeah
.
alr
you dont need either
its just
output = random.choice([".", ".."])
if output == ".":
...
else:
...
but
but?
never
if i get the same thing from output, what do i do
e.g. py output = random.choice([".", ".."]) if output == ".": output2 = random.choice([".", ".."]) # choosing again because i got "." and that's not what i want else: pass if output2 becomes "." again, what do i do
thats not my fault, its randomized
So you want a random choice but not really a random choice??
At that point you might as well hardcode it to be . with that logic lol
Yeah
choices to choose from: [roleobj1, roleobj2, roleobj3, roleobj4]
choice_role = random.choice(choices) - if the choice_role (a role obj) is in user's roles: do random.choice() again, keep choosing again till the role is not in user's roles
not sure if you understand, if not i'll try
then remove that from the list
if the user has all 4 of them? or 3 of them?
Why not just do random.choice([role for role in list_of_roles if role not in member.roles])
yeah
Way better then going over again until its empty
right that makes sense, thanks
Honestly you could just do random.choice([role for role in member.roles])
Did you read what they asked for? Because this would do 100% opposite of what they wanted
LOL, mb
ExtensionFailed: Extension 'cogs.statcord' raised an error: TypeError: Expected class deriving from discord.Client for arg bot not Bot
import disnake
from disnake.ext import commands
import statcord
class StatcordPost(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.key = "statcord.com-key"
self.api = statcord.Client(self.bot,self.key)
self.api.start_loop()
@commands.Cog.listener()
async def on_command(self,ctx):
self.api.command_run(ctx)
def setup(bot):
bot.add_cog(StatcordPost(bot))
i also have a red panda command and it uses the same website, whenever i try it, it gives me this error
@commands.command(name='redpanda', aliases=['rpan'], help='This command shows you a pictue of a red panda')
async def Red_panda(self, ctx):
async with aiohttp.ClientSession() as session:
request = await session.get('https://some-random-api.ml/img/red_panda')
dogjson = await request.json()
request2 = await session.get('https://some-random-api.ml/facts/red_panda')
factjson = await request2.json()
embed = discord.Embed(title="Red Panda", color=discord.Color.purple())
embed.set_image(url=dogjson['link'])
await ctx.send(embed=embed)
I recommend you use requests instead of aiohttp because requests doesn't require async.
Therefore, you could just do
import requests
@commands.command(..)
async def Red_panda(ctx):
r = requests.get("..")
d = r.json()
embed = discord.Embed(
title = "Red Panda", color = discord.Color.red()
)
embed.set_image(url = d["link"])
await ctx.send(embed = embed)
anyone?
but do you know how to fix the error?
let me test
alr
thats blocking
as nova said it will block dpy is a async lib?
You're trolling
that wasnt funny imo
wasnt supposed to be, gtho
can someone help eh
Then why do it?
If you don't think it's funny what's the point
because I can.. are you in control?
so you purposefully recommended bad thing? thats so evil dude
yeah
and against the rules
go cry.
bruh
i mean, i can report to mods
stop trolling
^
kk go ahead
<@&831776746206265384> ^
trolling and giving bad advice
Also being moderately toxic
There, I fixed
it was a mistake, I am currently tired
they will decide that
ok
But you admitted you were trolling
No it doesnt
and the, ahem, async
digging your own grave
!mute 924590198313086976
using aiothttp wont be hard ... ```py
import aiohttp
@command()
async def cmd(...
async with aiohttp.ClientSession() as session:
res = await session.get('url')
json_data = await res.json()
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1641107596:f> (59 minutes and 59 seconds).
get some time off discord, you need it
await
chill leave him be
yes , thanks for correcting!
mods have it all under control leave it to them
theres a bracket and : missing too
he just woke up
They'll figure it out
no.. ?
damn, what happened here?






