#discord-bots
1 messages Β· Page 15 of 1
over 90% webs use js either solo or with some other languages
people use html and css for something static and then they just use JS or TS ofc with libs depending
Oh oh π³
And joe π³
Well i dont mind.
Ok lads is there anyway to keep my discordbot online or just basically host it(im coding it in termux for fun)
can we go back to topic?
Replit.
vps
NO
#965291480992321536 check pins
no pls no
i use replit
Oh well my bad my bad
replit sucks
replit is the worst option
lemme just shoot you
whats wrong w that πππ
π« ok here
More like whats wrong with this chat.
rate limits
shared ip
check pins in the #965291480992321536 channel
i mean on my phone i use pydroid.
it has a long messages describing why Not to use replit
Thats okay ig
oki thanks guys
Yw loool
How can i make a command that can stop this?
i think pydroid is good for mobile hosting.
what do you mean by stop??
Stop the loop
In what way
break?
why, just use a task
uhm break
Discords rest api is just screaming at you
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
also this yeah ^^
Ye but how can i make a command for that?
you're pointing to break
okay you wanna break it but how will you do that
you can't access a variable in other function's scope until you make it global
I know im too tired for this π
because somethings easy doesnt mean it should be considered an option.
but that will keep you limited to only one person using the command at a time
No need to attack me.
So a stop and start command???
Yes
how do you think will stop command work
i never directed the message at you, it was pointed at the general/everyone.
Using if?
Hmm okay
i dont get you, gl, im gonna try to fix this shit
try
count = 0
cont = True
@client.command()
async def count(ctx):
while True:
if cont is False:
break
elif cont is not False:
time.sleep(1)
await ctx.send(f"Number {count}")
count += 1
@client.command()
async def stop(ctx):
cont = False
await ctx.reply("stopped.")
first syntax error
Just, why.
Good?
second wtf...
π
Why would you use that π
third, what's the point of that command.
you can just provide an argument to the command for how many times you want that message to be sent
So what im going to do im eating at CHOE KING
lol mb mb
!d time-str this makes life easier
No documentation found for the requested symbol.
!pip time-str
for x in range(1,999): like that?
Could that work??
True
Or not at all
it will work.
Whats the point of the command either way lol
spamming
well that's easiest way probably, I just made my own classes for time
i can think of an use-case, ||being annoying||
oop = good
p π
also logs are good
Huh
i can think of 3-4 things when someone says "logs"
Does x= False do anything?? would that stop a while in range loop or am i dumb ash
Im just playing random cenarios in my mind lool
What has happened here lmao
nice pfp π
;))
okimii, hii
Heyyyy
heyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
@slate swan you're genius can u understand is my bot trolling me, cus wtf is this
wanna makeout?
mods can do it
can you show more of the error?

you should be using _Table__tablename__
waht?
what is that file and folder naming.... check your stuctures.py
!e ```py
class Table:
tablename = "F"
print(dir(Table()))
class bounded variables

why is it a dunder anyways?
if you want the value not to change or in theory ofc, just use a constant
@slate swan
@bot.command()
a=1 #whatever
async def start(ctx):
embed=discord.Embed()
while a in range(1,999):
embed.add_field(name="here",value="here",inline=True)
await ctx.send(embed=embed)
@bot.command()
async def stop(ctx):
a=False
await ctx.send("Stopped.")
that should work.
im leaving
idk what they wanna value it
so i should do in __init__, self.__tablename__ = something?
but when I define Table var I set it, no?
you shoulndt be using dunder names for class variables at the first place 
you should get bonked
:(((
making me have a brain fart π
that's the value for the instance, not the class, you are using cls.__tablename__, not self.__tablename__
uhhh im dumbass
dubstep
lol
im out of ideas. what would be a good name for a decorator used to add a command to a Bot object
Bot.command most common way
Bot.slash_command/Bot.user_command diff decorator for each command type
Bot.with_command seems a bit nice
Bot.register ( ive been using this till now )
Bot.address ?
i got it from the topic of memory allocation
finally it worked:)
now fix your file naming or else
too understandable
so you want the user to have a brain fart each time using the deco, good idea

i'd name it Bot.okimii
why would you
because that decorator does nothing
but add a dict key-pair value
i hope you stub your toe at night you piece of cutenessπ
my lib does the same, it saves the instance of the function and the key is the event lol
did i ever finish my discord api wrapper, no, reason: im lazy.
what's wrong
youre using CamelCase to name your files, no good
thats a sqlite table Okimii
no, there was another file
MySQL
Why My DB Package Can't Be CamelCased
i name my files with -
_.py π©
well , python convention
modules and packages should be named in snekcase
_.txt.py
it was your whole folder
Wdym whole folder
camelCase <= this is camelCase btw
CamelCase is PascalCase
everyone except this is not cameled
nope, my teacher learnt me that this is CamelCase and this is lowerCamelCase
dont talk to meπͺ
no hes right, camelcase has variants lol
I dont understand that much
camelCase is generally referred for lower camel case
until you explicitly mention the Upper camelcase aka PascalCase
this gud? @slate swan
no, name your files better
you have poo naming skills
Yes:(
conventions for module names is flat case right?
back off
what
???
Tf?
whats wrong with them!!
you dont say anything in our dmsπ³
exactly, i dont say anything there
i need an angel shot
Who?

the guy in the blue shirt
hes getting aggressive π¨
But im in blue...
exactly

How do you know??!
i know everythingπ³
π³
Wait i think its purple
anyways gotta goooo to my husbands dms i go
!ot and i think its OT
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
looking for someone to help me with python code, "bot commands", dm pls
just ask in here
ok
Mommy @slate swan will help you

π³
error:
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "randomgif" is not found
can u help me name them then?
code?
i dont even know how im going to name my child i was thinking sarth jr but forget it, sure i can help you
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix=">", intents=intents)
bot = commands.Bot(command_prefix=">", intents=intents)
async def giphy(ctx, *, trending) -> None:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
π€¨
Eyo nothing sus bro π³
π§
why do you have two instances of Bot 
one is on_message and one is for bot commands
is that not ok?
just have one for both
I wonder if i can cook Pikachu aka electric ill
which one? for both*
i've gtg you can just send names and ill come back and name files)
bye
bot is a more accurate variable name
why??
cuz i need to use both for some reasons
No Okitler jr.
so if i choose either one and delete the other, will my code work?
with both on_message and bot commands

will it work?
just use botπΏ
so do i need to remove client? is this the reason why my code no work?
i dont know if thats the reason. but yes, remove client
then will i still be able to use on_message?
i would use bot.listen() so it doesn't disable commands
mhm kk
Yeah and with listen you can listen to the same event in many functions
NameError: name 'client' is not defined
client = commands.Bot(command_prefix=">", intents=intents)
when i removed this its error
pls help
#on_ready
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
send_message.start()
you removed client... so now you use bot
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
not really
even if you could you would have licensing issues
ahhh
ight iam a little new to all this so my bad
iam working on my first discord bot right now and getting the hang of things
error:
discord.ext.commands.errors.MissingRequiredArgument: trending is a required argument that is missing.
Code:
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=">", intents=intents)
async def giphy(ctx, *, trending) -> None:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=myapikeyhere&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
pls help, this is giphy api
command not working
you really shouldnt make a session on each call of the command and use context managers
then how?
how did you run the command
randomgif
discord.ext.commands.errors.MissingRequiredArgument: trending is a required argument that is missing.
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=">", intents=intents)
@bot.command(name="randomgif")
async def giphy(ctx, *, trending) -> None:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/trending?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)
so, the command is working fine. You didn't give it the trending parameter
@slate swan yw ^
ahhh, well you did a favor for my eyes
lol
i should be thanking you lmfao
Nahh your good.
i did bro
.
you said you did >randomgif
not >randomgif value_of_trending_param
what even does that mean?
why did you put trending in async def giphy(ctx, *, trending) ??
just for funsies or?
why i cant put?
bro-
so i just put it as
async def giphy (ctx) -> None:
yes or no? @vocal snow
or how?
This is like 1 h conversation
π³
so how??
@commands.Cog.listener()
async def on_message(self , message):
bucket = self.message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if message.author.id == 990358952632021043:
return
else:
if retry_after:
pass
else:
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +10}})```
i want to fix this to a channel and a role !! i know check.has_role but wot about channel ?
@slate swan when you define a command like:
@bot.command()
async def foo(ctx, arg1, arg2):
...
and then you call it in discord using >foo 1 2
what your library basically does internally is foo(ctx, 1, 2)
its exactly like how you call a normal python function so you can set default values to make it optional
so how esactly do i change it?
Ryuga's foo examples >>>>> , hahahahha
do you know how to set default values for parameters in a function?
!e
def foo(a, b=1):
print(f'{a = } {b = }')
foo(1, 2)
foo(2)
pls would u teach me how to make this command work
have been working on it for hours
@paper sluice :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | a = 1 b = 2
002 | a = 2 b = 1
and?
the thing is, you are not using the trending param inside your function, why do you have it there? are you going to use it later on?
if i remove it, it doesnt work?
are you asking me if it doesn't work or ...?
it would work because you don't use it anywhere
then how do i remove it?
there is a key on your keyboard, its called "backspace", put ur cursor on trending and press that key a couple of times
async def giphy(ctx, *) -> None:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
is it like this?
remove the * as well
k
if you want to, python doesn't care
async def giphy(ctx) -> None:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
is it like this?
so much error:
Warning (from warnings module):
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 71
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
RuntimeWarning: coroutine 'ClientSession._request' was never awaited
Ignoring exception in command randomgif:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 71, in giphy
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
AttributeError: '_RequestContextManager' object has no attribute 'json'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/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: AttributeError: '_RequestContextManager' object has no attribute 'json'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f818b724070>
you need to await session.get, then use .json on it
im dumb which part do i need to await?
i'd recommend using async with for creating a ClientSession since it closes once its done
show how?
or just make a bot variable and use it throughout when its running then override Bot.close() and close the session there
no
k
thxs u
async def giphy(ctx) -> None:
async with aiohttp.ClientSession() as session:
session = aiohttp.ClientSession()
response = await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g").json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
is it like this?
^ and you should await session.get
its already awaited
no, json is
the json coroutine is being awaited not the session.get
then how do i await session.get?
use parethesis to execute the request first and then use the coroutine on the obj the method returns which is the payload the api returned
show how
code*
await (await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g")).json()
ok
and what else do i need to fix? or thats it?
and why are you using context managers but you're starting a session inside of the session
@bot.command()
async def report(ctx, user: discord.User, *,message=None):
embed=discord.Embed()
embed=discord.Embed(title="Report from {ctx.author}",description=message,color=0xffff00)
embed.set_footer(text="Report Command !")
await ctx.author.send(embed=embed)
Any way you can make it so you can old send a message to a mod??
like certain role
you forgot the f in the f string lol
My bad
Ignoring exception in command randomgif:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/bai/Documents/Personal Things/Do not delete/Only viewable by me/Aww Pika Discord Bot/aww pika discord bot.py", line 77, in giphy
urllist.append(event['images']['original']['url'])
TypeError: string indices must be integers
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/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: string indices must be integers
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f85a4f6f580>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f85a51487c0>, 21.886284383)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f85a4f6f550>
error
Ill add it but can u help?
like send a message to all members that have a certain role?
Code:
async def giphy(ctx) -> None:
async with aiohttp.ClientSession() as session:
session = aiohttp.ClientSession()
response = await (await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g")).json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)```
how to fix this error?
Code:
@bot.command(name="randomgif")
async def giphy(ctx) -> None:
async with aiohttp.ClientSession() as session:
session = aiohttp.ClientSession()
response = await (await session.get("https://api.giphy.com/v1/gifs/random?api_key=0wht0K4drtVOM4tZOJCK2iwqNkAND5HJ&limit=25&rating=g")).json()
embed = discord.Embed()
urllist = []
for event in response['data']:
urllist.append(event['images']['original']['url'])
embed.set_image(url=random.choice(urllist))
await session.close()
await ctx.send(embed=embed)
There u go
you dont need session = aiohttp.ClientSession()
well it depends you can fetch the member by his id
and dont close connection manually, thats what the contextmaanager is for
How would it look like??
oh ok and what else?
someone help.
@bot.command()
async def report(ctx, user: discord.User, *,message=None):
member=988844917163954266
embed=discord.Embed()
embed=discord.Embed(title=f"Report from {ctx.author}",description=message,color=0xffff00)
embed.set_footer(text="Report Command !")
await ctx.member.send(embed=embed)
Can't get it to send a dm to a mod/owner
ctx.member isn't a thing
I just figured lol
are you trying to message the mentioned user or
yeah but make it so u can only dm a user w a certain role
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
use this decorator
I don't think that's what he wants
so you want to message user if they have a specific role
oh, you want all mods or whatever to get a dm?
in pycord can i give context to my view?
like if i wanted to see if interaction user id was the same as ctx.author.id
with bots whats the best way to get a category id/ create a channel in a category without creating the category each time
category = await guild.create_category("JOBS")
await guild.create_text_channel(jobid,Permissions=perms,category=category)``` currently using this
creates a new category each time whereas i want to create the channel in the existing category
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
if you have the category id
the class is CategoryChannel so I believe so
I'll give it a go thanks
May I ask what's difference if I use discord.py and discord.js?
I feel like Python bots are much easier to make and maintain
that javascript is ||shit||
tried creating js bot and had to do slash commands in seperate files D:
discord.js has support for voice receive, discord.py doesn't. I think that's about it if you're talking about API coverage
what is um how to fix 404too many requests error,how long am i blocked for
Wdym voice recive
utilities for receiving voice data from voice channels
help
what can we use that voice data for?
please
anything you want
like i cant make music bot with python or something?
storing conversations, other stuff
ignored
sure, but that's sending data, not receiving it
imagine music bot where you say "pause" or "next-song" it does accordingly
danm
but it would be pretty unaccurate and buggy to use since not a lot of people has good mics
||thats a nice idea||
it should say in the error. You get that when you spam the api and break ratelimits
I am currently making a dashboard for my bot with django and I still gotta use js for frontend (I copypaste it π)
ooh
ppray..?
Damn you got cloudflare ban
my hopes π
Idk if cloudflare bans are stricter than common ratelimit but discord mentions it specially in the docs
I never got ratelimited myself so I have no idea what that is
what are cloudfare bans
await asyncio.sleep()?
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@commands.Cog.listener()
async def on_message(self , message):
if message.author.id == 990358952632021043:
return
bucket = self.message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
pass
else:
bal = await economy.find_one({"id": message.author.id})
if bal is None:
await self.open_account(message.author.id)
else:
amount = random.choices([random.randint(0, 10) , random.randint(11, 20) ] ,weights = (0.9, 0.1) )[0]
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +amount}})
await message.channel.send(f'{message.author} gets {amount} in PAODs bank')```
how can i make this same thing for vc so i can give tham some paods/xp ????
this is for chat hmm π³
any idea any one or suggestion ?
Hi im struggling with something. Im new to python trying to build a discord bot using pycharm and python
pip install -U discord.py
Should i type that where
in terminal
to install discord.py lib , its not in build lib
I did install this
If your goal is to learn python I don't recommend starting from a discord bot as it is a complex application, however if your goal is to make a discord bot.. well still not a good idea to try and make it without basics knowledge
whats your file name ? is it discord ?
No its ||my discord bot.py||
π€
Also could you like use screenshots
The code is on my laptop and disc is on my phone
@vale wingwot about this , any idea ?
I don't even understand what this code does
if a user typer something it gives 10 xp to user in 60s intervell !!
i want same for vc's like a user is in vc for 1 min he get 10 xp
Interesting how you used the bucket for cooldowns
Personally I have a sort of dict with datetimes
π lul
ohh like ? gimme a sort code how yours work
?
And uh what's +amount
its a random value from 0 - 20 in which no. have weights
okk k let me see
?
send your full code pls
Run a code formatter for this
π
Tf is wrong with your fonts
Idk
It's supposed to look like this (don't pay attention to code itself)
I didn't change anything. It is just liked i downloaded it
And did you take any tutorial
On what?
its not "supposed" to look like that, they are just using a different font....
Discord bot
They said they didn't do anything
Yes
This is the default font so it is supposed to look like this
They have either some font issues or installation issues
π€
Could you link me that tutorial
What IDE do you have
Will dm you
vs code
ah k
@paper sluicelast line π₯² like for vc's ?
Dmed it to you
what is the problem?
@limber bison go to the settings and find this thing for python extension, choose whatever formatter you want, then right click in your code and choose "Format Document" it should do the thing
like this code is for chat xp , if someone chat it inc , but i want same think for vc too so whats my first step ?
for chats we know on_message hahaha
ohhh got it
or you can just pip install black and use python -m black file/directory/.
!d discord.on_voice_state_update maybe
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
and can i put check for an catagory ?
note that it just stated the connection, nothing related to the users voice activity
like i want a system if an user is in vc i want he get some level !!
Just count the time they have been in vc ig?
how can i do this ?
For example save the time when the user joined a vc and when they leave the vc add some score based on the time they have been there
Or use some kind of loop that would add score to every member in vc
The second approach is better because user doesn't have to leave vc to get score assigned but is slightly more expensive cause of the loops
Why it saying that something is missing
@client.command()
async def guess(ctx, variable: int):
await ctx.send(variable)
Thank you!
no problem, let me know if it still gives an error
How is that related to the error
You are just not providing variable argument to command
If name is not provided the function name is used
Im confused
How do you invoke your command
I mean what message do you send to execute it
.guess
Is variable argument supposed to be optional or
As long as it is not optional you gotta provide it to the command
?
How can i start first the command start
Em what
To prevent member guessing without saying .guess
You need an error handler
So basically you need to listen for on_command_error event
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this logs to the library logger, however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
And then check if exception is an instance of some error class, in your case commands.MissingRequiredArgument
A very basic error handler looks like this
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
text = "You are missing a required argument for this command"
elif isinstance(error, commands.CommandOnCooldown):
text = "This command is on cooldown, try again later"
else:
raise error
await ctx.send(text)```
@slate swan
Thank you for the code
If anyone is able to help me in #help-potato that would be awesome
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
Requirement already satisfied: discord.py in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (1.7.3)
Requirement already satisfied: aiohttp<3.8.0,>=3.6.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from discord.py) (3.7.4.post0)
Requirement already satisfied: attrs>=17.3.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (22.1.0)
Requirement already satisfied: multidict<7.0,>=4.5 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (6.0.2)
Requirement already satisfied: typing-extensions>=3.6.5 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (4.3.0)
Requirement already satisfied: async-timeout<4.0,>=3.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (3.0.1)
Requirement already satisfied: chardet<5.0,>=2.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (4.0.0)
Requirement already satisfied: yarl<2.0,>=1.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (1.8.0)
Requirement already satisfied: idna>=2.0 in /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages (from yarl<2.0,>=1.0->aiohttp<3.8.0,>=3.6.0->discord.py) (3.3)
WARNING: You are using pip version 22.0.4; however, version 22.2.1 is available.
You should consider upgrading via the '/Library/Frameworks/Python.framework/Versions/3.9/bin/python3 -m pip install --upgrade pip' command.
Anyone know what this is about?
!command
you already have the libraries you were looking for installed and a new pip version is available
when you install discord.py
how to disable the spammy effect?
await message.channel.send("hi")```
Navigate to your Applications/Python 3.6/ folder and double click the Install Certificates.command
or is there any replacement for if "hello" in message.content.lower()
i want it to extra hello from a sentence, but using in message.content.lower() creates a spammy effect
wdym with βspammy effectβ?
how can i type like this
test
` <- 3x before and after ur message. Make sure to add py after the first 3
thanks
Idk if that will work, Iβm on my phone rn but something like this:
```py
# Text here
at the bottom ` 3x again
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
kills me
ty, I forgot the cmd
@bot.command()
async def attack(ctx, user: nextcord.Member=None):
if user == ctx.author:
stupidityem = nextcord.Embed(title ="bruh :smh:", description = "HOW DA HELL ARE YOU GONNA ATTACK YOURSELF???? :stopit:", colour = nextcord.Colour.random())
stupidityem.set_footer(text = "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe ~ Albert Einstein")
stupidityem.set_image(url="https://c.tenor.com/-YrgmiDmNTsAAAAC/toy-story-stupid-people.gif")
await ctx.reply(embed = stupidityem)
if user == bot.user:
botem = nextcord.Embed(title= "β β β WARNINGβ β β ", description = "You have Initiated Skynet's Artificial Intelligence. Nukes are there all around the world and terminators surrounding.", colour = nextcord.Colour.red())
botem.set_footer(text = "Should have left me alone >:)")
botem.set_image(url = "https://c.tenor.com/HQnsUe-_ig4AAAAC/robot-tech.gif")
await ctx.reply(embed = botem)
else:
attackem1 = nextcord.Embed(title= f"You tried to Attack {user}, but...",description=f"{ctx.author.name} tried to punch {user.name}, but he caught it and kicked {ctx.author.name}!:kekw:", colour=nextcord.Colour.random())
attackem1.set_image(url="https://cdn.discordapp.com/attachments/905019001757892620/953280072834486312/spider-man-green-goblin.gif")
attackem2 = nextcord.Embed(title= f"You tried to Attack {user}, but....",
description=f"{ctx.author.name} tried to attack {user.name}, but he dodges it smooth as heck:kekw:", colour=nextcord.Colour.random())
attackem2.set_image(url="https://c.tenor.com/VzpuZphq0EgAAAAd/doc-ock-spider-man2.gif")
attackem3 = nextcord.Embed(title = f"You attacked {user} and...", description = f"{ctx.author.name} TURNED {user} INTO ***SPAGETTI***")
attackem3.set_image(url="https://c.tenor.com/IaTH9agWDIoAAAAd/doctor-strange-in-the-multiverse-of-madness-illuminati.gif")
embeds = (attackem1, attackem2, attackem3)
await ctx.reply(embed=random.choice(embeds))
I get both responses for some reason
Not a good fix but I suggest you return after you send the embed
Using discord.ui.View how can i keep my buttons always on
and not going into interaction failed after a while
!d discord.ui.View
class discord.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.
what is max timeout
timeout=None
It wonβt stay after bot restarts tho
how to reset shards?
Because use elif
heellp
Hello..anyone know why my interaction is failing again and again?
here is the code:
`await ctx.send(embed=embed, components=[Button(label="Report", style=3,custom_id="button-startreport")])
interaction = await client.wait_for("button_click", check=lambda i: i.custom_id=="button-startreport")
await interaction.response.send_message("Button clicked.")`
!e ```py
n = 50
if n > 40:
print("N > 40")
if n > 30:
print("N > 30")
a = 50
if a > 40:
print("A > 40")
elif a > 30:
print("A > 30")```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | N > 40
002 | N > 30
003 | A > 40
anyone?
I highly don't recommend implementing components this way, use subclassing instead (check for examples on github repo of your library)
@commands.command()
@commands.guild_only()
async def sync(self, ctx: commands.Context, sync_globally: bool = False) -> None:
async with ctx.channel.typing():
if ctx.channel.permissions_for(ctx.author).manage_guild:
if sync_globally:
await self.bot.tree.sync()
await ctx.reply('Slash commands have been synchronized globally')
else:
self.bot.tree.copy_global_to(guild=ctx.guild)
await self.bot.tree.sync(guild=ctx.guild)
await ctx.reply('Slash commands have been synchronized on this server')
else:
embed = discord.Embed(title='Action Error', description='You don\'t have the permission to use this command.',color=0x2f3136)
embed.set_thumbnail(url='https://cdn.discordapp.com/emojis/971007299038621727.webp?size=128&quality=lossless')
embed.set_footer(text=f'Requested by {ctx.author}')
await ctx.reply(embed=embed)
is this correct ?
Wdym reset shards
hmm alr
i mean if one shard was down id have to do smth right..?
Library automatically reconnects it once gateway is available
is there a way to see all the shard status?
And uh how many guilds is your bot in
64
You clearly don't need sharding
but what about the too many requests error
It's recommended to do it when bot is in at least 1k guilds and is slower than expected
oih
Replit?

Even if you shard it you can't avoid that error
will command cooldown help it
Get a VPS or smth, amazon AWS offers you 1 year of free tier and I can help with that
Nah it is because of other users hosting their bots on replit, you can't really do anything about it
oh
@slate swan interested?
"I can help with that"
alt accounts
Meaning I will explain all the stuff
ooh
Don't they have a verification
Checks ig?
and people can toggle it on and off
Or you mean slash commands
i mean a command
Prefix?
yes
That's kinda complicated, you gotta have a database
And as I am thinking about its structure it's complex
is json okay for it
Json is not okay for data storage generally
<= dumb
Config files and network data transmission is ok but storage no
Fr like how would it look
Rows for guilds and columns for commands?
Ig it's better to use a database which supports arrays like postgres
what about a variable
for every guild
like um
toggle = on
toggle = off
and um yeah
You gotta have a toogle for every command in every guild
Or for every guild in every command
okay so what if i have to use it in only command
a command which is like available for some servers
and others not
how do i do it
Or like server admins can toogle it on and off
server admins]
Then hardcoding won't work
i hvave this thing in on_message
Oh I have an idea about the database structure for that stuff
So uh guild_id | command_name | is_enabled
It's much simpler than I was thinking
You can actually put only disabled commands to there not to create useless rows
Otherwise you are going to have guilds amount * amount of commands rows and that's useless
And if a command is not present in a table you just consider it enabled
nooo not thattt
In postgres you could actually do guild_id | disabled_commands and it would be better imo
Um then what do you mean
forget about it ,its hard to explainn
its off now but on one refresh it become on
ngl logo looks amazing
thanks
def add_buttons(self):
moves = iter(self.moves)
async def move(interaction: Interaction):
print(f'You used {button.label}')
await interaction.response.send_message(f'you used {button.label}')
for i in range(6):
button = Button(label=next(moves, "Empty"))
print(button)
button.callback = move
self.add_item(button)``` why always say empty when i press button in discord py 2
Is it a just created bot
Does it have tags and "add bot" button configured
This button
Disable this thing in oauth2 tab
Weird, my bot doesn't have that badge even when it has application commands
I am not sure how they actually give those badges
They check if a bot has any of the 3 application commands command(s)
I have a suspect that it actually depends on amount of commands
done thanks buddy !!!
iirc according to their announcement u need at least 1 app command
Because I had a bot that had like 5 app commands but recently I rewrote it to around 30 of them and now it has that badge
Weird
Yeah
I am having a problem with my discord bot
bot = commands.Bot(command_prefix = ".")
@bot.command()
async def lobstercage(ctx, arg1, arg2):
await ctx.send(f' You sent {arg1} to the lobster cage for {arg2} minutes')
however this isn't working
They key word is testing, probably discord doing that on random bots like they once were doing with animated banners for users
whats not working
It may need to be verified?
how to sync the slash commands ??
I type .lobstercage test 30 and the bot doesn't send the message
look in the pins
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
does the bot turn on? any error messages
bot turns on fine, got some bot.event code running just fine
do you have an on_message event?
yes
does your bot have the correct permisisons
and do other commands work fine?
it has admin prems
Probably. I missed that, sorry
it has no other commands at the moment
May I see your on_message event?
you may need to add this at the end of it
await client.process_commands(message)
@bot.event
async def on_message(message):
print(f'{message.author} has said {message.content}')
wdym at the end of it
@bot.event
async def on_message(message):
print(f'{message.author} has said {message.content}')
await client.process_commands(message)β
cant get the indent right but make sure its inside the function
A database probably
TabError: inconsistent use of tabs and spaces in indentation
yeah try fixing the tabs, im on a phone rn and its kinda hard
await client.process_commands(message)β
just add that below the print
and be sure its inside on_message function
can someone help me with discord interaction buttons
File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 398, in start
self._task = asyncio.create_task(self._loop(*args, **kwargs))
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/tasks.py", line 381, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop```
bot.changeable_activites = (
"Call of Duty: Warzone",
"Fall Guys",
"Fortnite",
"Call of Duty: Black Ops IV",
"Sea of Thieves",
"League of Legends",
"GTA V",
"Valorant")
@tasks.loop(minutes=1)
async def change_activity():
await bot.wait_until_ready()
new_activity = random.choice(bot.changeable_activites)
await bot.change_presence(activity=discord.Streaming(new_activity))
change_activity.start()
You need to start it in the setup hook
@bot.event
async def on_message(message):
print(f'{message.author} has said {message.content}
await bot.process_commands(message)
still does not work
gives me a taberror still
huh
gladiator colette
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Yes
class Moves(View):
def __init__(self, ctx, moves):
super().__init__()
self.moves = moves
self.ctx = ctx
self.add_buttons()
def add_buttons(self):
moves = iter(self.moves)
async def move(interaction: Interaction):
print(f'You used {button.label}')
await interaction.response.send_message(f'you used {button.label}')
for i in range(6):
button = Button(label=next(moves, "Empty"))
print(button)
button.callback = move
self.add_item(button)``` i have this code and i am trying to make a list of moves appear as buttons and it works but when i press the buttons it always prints empty even if the button is called something else
I removed the whole block of code that prints every message into my console and now my .lobstercage code works
i may be wrong but on_message event kinda overwrites how the bot processes commands
well that stinks
so you need to add that thing i sent to fix it
if im using digitalocean which droplets plan should i use? my bot is in less than 100 servers and doesnt really do any heavy duty tasks
Pick the cheapest one
1gb ram is totally enough
But if you got free credits get the one you can use for free until they expire π
idk if this is related but shouldn't interaction: Interaction be interaction: discord.Interaction?
Yeah just use @bot.listen() instead of @bot.event
i did from discord.interactions import Interaction
oh ok
If you use @bot.event you overwrite the default listener
I got it to print and still be able to use my command
turns out
bot.event
async def on_message(message):
await bot.process_commands(message)
print(f'{message.author} said {message.content}')
putting the await first works
good
goose
You can also do this
Remove await bot.process_commands(message) completely and do this instead
@bot.listen()
async def on_message(message):
...```
It'd be better if he actually done this lol
That's a pretty useful thing
yep
Allows you to create several listeners for one event
You avoid having 100 lines in one event
Yeah and you do stuff asynchronously which is an advantage too

Imagine making discord bots
π
I once thought of that thing
The bot for hosting bots
For making bots there is already one and it is cringe as many say
mee6 has something that's similar
You can get a custom mee6
or something like that
You could actually clone bot's github repos, add dockerfile and compose and just launch the container (some volumes stuff and secrets too ofc) but if many people wanted to host their bots you would need a whole data center
Or you could limit the ram usage but you'd still need a lot of computing power to host that many bots
And yeah ratelimits
So not good
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content == 'hello':
await message.channel.send('Welcome to the server!')
if message.content == 'cool':
await message.add.reaction('\U0001F60E')
Whenever I type hello I get a response message from the bot but when I type cool the bot won't respond with an emoji
You made a small typo: not add.reaction, it's add_reaction
how do I remove logging certain messages from certain people
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.author == 'SpookyBot#0745':
return
else:
print(f'{message.author} said {message.content}')
I have this line of code but it still prints to my cmd
I just want to silent my bots
if message.author.id == id
thanks It works
no problem
in discord py 2 how do i set a button label to be a variable
Subclass discord.ui.Button, and pass it into the constructor
im not sure how to do that
i did something simlar like this
def add_buttons(self):
moves = iter(self.moves)
for i in range(6):
test = Button(label=next(moves, "Empty"))
print(test)
async def move(interaction: Interaction):
print(test)
print(f'You used {Button.label}')
await interaction.response.send_message(f'you used {Button.label}')
test.callback = move
self.add_item(test)1```
it works but i cant get the button name after i make the buton
i tried a lot o diferent things
This is not quite ideal due to the nesting, and it's hard to follow
You might want to subclass both view and button
class TicTacToeButton(discord.ui.Button['TicTacToe']): what do the brackets mean
It's not necessarily but hints to your IDE/linter what the type of self.view is
Hey so i was wondering if it is still possible to make discord bots with python, I haven't kept up with it and I heard there has been a lot of changes.
For sure! Python is still dominating in the discord bot development space
wait why i need to subclass if i can do this test = Button(label=next(moves, "Empty"))
Having to nest your callback function and do something like test.callback = callback
So i want to get back into it but Ever youtube vid i find is outdated and old and not sure if it would still work.
It's not very pythonic, and disoragnized, if you ask me
oh ok
Yup, most of the youtube videos for discord.py are outdated and even if they weren't, they're terrible. The best ways to learn is by using the documentation and the examples, and even better, asking for help around here
Okay Thank you
@guild_only() is this correct check ?
class Move(Button):
def __init__(self):
super().__init__()
async def callback(self, interaction: Interaction):
await interaction.response.send_message(self.label)``` something like this will work\
You want to change the label?
i want print label
Yup that will work
Right, but you should have a way to pass in label into the constructor
can you just do Move(label='a')
That would throw an error
!d io.BytesIO
class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.
The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.
[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
off topic for here i think
class Move(Button):
def __init__(self, label):
super().__init__()
self.label = label
async def callback(self, interaction: Interaction):
await interaction.response.send_message(self.label)```
class MyButton(discord.ui.Button):
def __init__(self, label: str) -> None:
super().__init__(label=label, ...)
self.label = label
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.response.send_message(self.label)
class MyView(discord.ui.View):
def __init__(self) -> None:
super().__init__(...)
self.add_item(MyButton("Button #1"))
self.add_item(MyButton("Button #2"))
self.add_item(MyButton("Button #3"))
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
view = MyView()
await ctx.send(view=view)
This, for example, will send a view with 3 buttons, and when the user clicks on it, it will respond with the button they clicked on
oh ok
def add_buttons(self):
moves = iter(self.moves)
async def move(interaction: Interaction):
print(f'You used {test.label}')
await interaction.response.send_message(f'you used {test.label}')
for i in range(6):
test = Button(label=next(moves, "Empty"))
test.callback = move
self.add_item(test)
``` i am wonder why this not work and always sends Empty even when label is something else
Not sure. The code is hard to follow and there may be an error anywhere
Which is why I suggested subclassing it
ok is working now thank you very much
can the callback function return something
actually i can just test that
It can but it'll be ignored, so probably not a good idea
ok thank you for your ehlp
I want to create a command to where it takes in two inputs (username, time) and gives that user a role for that amount of time would anyone know how to do this
I am trying to test something for Betterdiscord could someone check the code for me?
Does anybody know why this code isn't working?
@client.event
async def on_guild_join(guild):
for channel in guild.text_channels:
print(channel.name)
output:
e
channels in the server:
I am trying to test something for Betterdiscord could someone check the code for me?
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
We can't help with that as it's in violation of Discord's TOS
Its an avatar viewer so it fullscreens their avatar
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
^
this is a very moment
do you have guilds intent enabled?
in my code?
nvm I read half the thing
what does guild.text_channels print?
so either the text channels arent cached properly
@sick birch thanks for the review on that PR, now it got 3 more reviews and I am waiting for 2 of them to re-review cause they requested changes, but after they approve the changes what is going to happen before the PR gets merged?
"e"
oh shoot I forgot to save file

yeah its just "e"
where did i do an indentation error?
space at beginning of @bot.event
oh thank you :)
wait
oh its a parsing error
I've gotten that a lot
inconsistency in spaces and intentdations?
sometimes its because you are using both spaces and indentations
yw
sad, really sad, it's probably caching issues in that case
f
ok
i guess i don't even have to make my own help command, this looks good enough :lemao:
cus im trash designer
I think that is cogs?
do you also need to enable intents in your code
u can either use a docstring or u can set up some custom kwarg either way works
ah ok
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I want to create a command to where it takes in two inputs (username, time) and gives that user a role for that amount of time would anyone know how to do this
Yeah sure you just need a database in which you will store the time at what to take the role off and a loop that will periodically check for those roles
I could link an example but it's kinda complicated so I won't
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Ibrah\Desktop\discordbot-main\main.py", line 15, in on_ready
await bot.change_presence(activity=discord.Game('Sky Craft'))
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
ah
!error
!error File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Ibrah\Desktop\discordbot-main\main.py", line 15, in on_ready
await bot.change_presence(activity=discord.Game('Sky Craft'))
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
where are you changing that? 
IDK
nvm, ah on_ready, just dont
wdym
dont changr your presence in on_ready 
O
Ok Then
Thank You!
either change it in the bot constructor or a task
Traceback (most recent call last):
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Ibrah\Desktop\discordbot-main\main.py", line 24, in on_message
await bot.change_presence(activity=discord.Game('Sky Craft'))
File "C:\Users\Ibrah\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 1062, in change_presence
await self.ws.change_presence(activity=activity, status=status, afk=afk)
AttributeError: 'NoneType' object has no attribute 'change_presence'
haha if message.content.startswith("!hi"): await message.delete() await message.channel.send("Hello Friend How I Can Help You? :blush: ") await bot.change_presence(activity=discord.Game('Sky Craft'))
what evemt
it's in on_message now, nice
read the error, bot is None
wdym
i so dumb 
Wtf
I Don't understand
Sorry today is frist day me in python
i know java :)
but not python
e
just to ping you
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
can make java bot??
import discord
from discord.ext import commands
import json
import os
key = "e"
bot = commands.Bot(command_prefix='!')
client = discord.Client()
random = ['MayBe' , 'Yes' , 'No' , 'Probbly' , 'Likey' , 'unlikey']
@client.event
async def on_ready():
print("BOT ONLINE")
channel = client.get_channel(1004036302594920508)
await channel.send("I Am Online β
")
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("!hi"):
await message.delete()
await message.channel.send("Hello Friend How I Can Help You? π ")
await bot.change_presence(activity=discord.Game('Sky Craft'))
if message.content.startswith("!user"):
await message.delete()
await message.channel.send(f"Hello {message.author}")
if message.channel.id == 1004054901787201646:
channel = client.get_channel(1002154446442209393)
await message.delete()
await channel.send(f"Test bot Server Β» {message.author} Β» **{message.content}**")
if message.channel.id == 1002154446442209393:
channel = client.get_channel(1004054901787201646)
await message.delete()
await channel.send(f"Sky Craft Β» {message.author} Β» **{message.content}**")
if message.channel.id == 1002154446442209393:
channel = client.get_channel(100215444644220939)
await channel.send(f"{message.author} Β» **{message.content}**")
if message.channel.id == 1004054901787201646:
channel = client.get_channel(1004054901787201646)
await channel.send(f"{message.author} Β» **{message.content}**")
@commands.Cog.listener()
@commands.guild_only()
will this word ?
e
Sure... using something like Discord4J or JDA
WTF
You can practically make a discord bot in any language these days
Excluding esoteric ones, of course
ook ls help me in this
how can i remove a member from a channel?
read_messages=False, send_messages=False dosent actually "remove" the member
idk
What type of listener?
you dont need Client and Bot instances together as Bot is a subclass of Client and has all the functionality that the Client class has and the reason bot.ws which is the websocket that connects your code to the gaetway is None because you are actually running client instead of bot, so remove the Client instance and use only the Bot instance
wait
let me read step by step
just add a conditional, if guild_id != your_guild_id: return
depending on your event, check if the guild exists
@commands.Cog.listener()
@commands.guild_only()
this will not work right ?
for example, for on_message, check if message.guild is not None.
oh k
I am back again π
message.guild will be None if there is no guild, just go by this assumption
No, those are for commands
ew ew that looks bad just to even look at
@commands.Cog.listener()
async def on_message(self , message):
if message.author.id == 990358952632021043:
return
bucket = self.message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
pass
else:
bal = await economy.find_one({"id": message.author.id})
if bal is None:
await self.open_account(message.author.id)
else:
amount = random.choices([random.randint(0, 10) , random.randint(11, 20) ] ,weights = (0.9, 0.1) )[0]
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +amount}})
await message.channel.send(f'{message.author} gets {amount} in PAODs bank')```
i want to make this command guild only
yes.
oh k k
that's a listener
not a command
and just add a conditional as I said
@commands.Cog.listener()
async def on_message(self , message):
if message.guild != None:
if message.author.id == 990358952632021043:
return
bucket = self.message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
pass
else:
bal = await economy.find_one({"id": message.author.id})
if bal is None:
await self.open_account(message.author.id)
else:
amount = random.choices([random.randint(0, 10) , random.randint(11, 20) ] ,weights = (0.9, 0.1) )[0]
await economy.update_one({"id": message.author.id}, {"$inc": {"PAODs": +amount}})
await message.channel.send(f'{message.author} gets {amount} in PAODs bank')```
this will work i think
gimme a sec
Just a tip to write better code: you can also avoid the extra indentation for the entire listener if you aren't adding an else: clause by inverting the boolean logic and adding a return statement. That was probably a confusing sentence, so here's an example:
async def on_message(message):
if message.guild is not None:
...
# unnecessary indentation
async def on_message(message):
if message.guild is None:
return
... # no extra indent
is it possible to put video/audio files in an embed? or do they have to be sent outside of it?
it is possible
no typehints 
@commands.Cog.listener()
async def on_message_delete(self, message):
if not message.author.bot:
embed=nextcord.Embed(title="Message delete", description= f"Deleted by {message.author.mention} in {message.channel.mention}",color=0xfd9fa1, timestamp=datetime.datetime.utcnow())
fields=[("Content",message.content,False)]
for name, value, inline in fields:
embed.add_field(name=name,value=value,inline=inline)
if value is None:
value="_ _"
i=1
try:
embed.set_image(url=message.attachments[0].proxy_url)
await self.bot.get_channel(933978399280599080).send( embed=embed)
while i<len(message.attachments):
await self.bot.get_channel(933978399280599080).send(message.attachments[i].proxy_url)
i+=1
return
this is my message to log deleted messages. how can i make it work for video and audio files too instead of just pictures?
it clutters the code when im trying to prove a point lol
it should work without explicitly having to do anything or if anything is required then the type of the embed maybe

