#discord-bots
1 messages · Page 1054 of 1
Bruh if the error is saying that the token is wrong then it is wrong, check it again
k i double checked
it is correct
i do have a uptime robot monitor on a website created by
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "I'm alive"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
and i get this also
How to ignore specific command for a guild?
In replit.com you often do os.environ["TOKEN"], not .getenv. Replit doesn't support .env files, that's why they have their own.
You could use a check, or a decorator perhaps
Ratelimited
that is why you should not use repl.it, it has shared IP so ratelimits are shared
!d Member.joined_at
!d discord.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild.
If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
Loop through the members and check against this attribute
[] not ()
How to show preview like this?
It's an Embed
os.getenv(key, default) is equivalent to os.environ.get(key, default), so that's not really a problem
Like it is showing an aware of datetime that one
thats the embed description
hi how can a discord bot detect if someones online? :)
!d discord.Member.status
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.
tnks
Yeah But It Is Taking The Description From Website i am saying that
How would we take the description from website
it uses webscrapping iirc
!src d
Look up documentation for Python symbols.
check the source code
Ok
The bot makes a GET request to the docs, with the objects.inv endpoint, then it decompresses the bytes it received from that endpoint, then parse it based on your input.
😔id love it if there was a way to do it "safely" without making web reqs since all the docs are in the src and its saved on the device itself
is there a website where i can see all the events things
The docs listed all available events:
Discord Event Reference - https://discordpy.readthedocs.io/en/stable/api.html#discord-api-events
ext.commands Event Reference - https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#ext-commands-api-events
thks
WHY
Show the full traceback, you just cut an important part
!traceback | You missed the last part of the traceback.
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
why the bot is not runnig
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
if you are hosting on repl.it you are probably using uptimerobot to keep the bot alive by pinging every few minutes, which causes the bot to be temporaily blocked by Discord
He's using replit so
Looool replit
import discord
import discord.ext.commands
import discord.state
import os
client = discord.Client()
client.run(os.getenv('TOKEN'))
I got a weird error
It returns this on the client = discord.Client() statement:
error says it all
since v2+ the intents kwarg is required
import discord
import discord.ext.commands
import discord.state
import os
client = commands.Bot(command_prefix="your prefix",intents=discord.Intents.all())
client.run(os.getenv('TOKEN'))
I ran the same code 1 month ago, and it worked before, so its weird.
I can't use client = discord.Client()?
no
maybe
discord.py 2.0 requires intents for Client, while discord.py 1.7.3 does not require intents to be passed in, so if you degrade back to the stable version (1.7.3), You could use Client just as fine without passing in intents
there should be a valid reason why he wants to be on v2, else I'd just downgrade to v1.7.3
application commands could be the main motive of using Client on 2.0
why?
What were you doing with that website?
uptimer?
Then you probably made too many requests and got ratelimited / blocked
i change repl and now it works
oof, replit
?
.
The replit IP you were connecting from made over 10,000 4XX requests in the last ten minutes, meaning Cloudflare blocked you from accessing the site
what site discord?
yes
but i created a new repl and now it worked?
It assigned you a different IP
is it because i ran it multiple times?
The same thing will likely happen again soon
am i the only one who use the ip?
Let's read together
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
nani!
How to send an error message using slash commands which only the author can see and noone esle?
the term you're looking for is "ephemeral"
it's a kwarg in the send_message method
what software can i use?
that ran 24 hours
is github the same?
#discord-bots message
there are 2 links you know
so im not the only one on that ip?
well read!
Can you pls give an example?
If I want to get the first 100 members who joined the server, I can do something like this?
ordered_members = sorted(guild.members, key = lambda m : created_at)
return ordered_members[:100]
i did! i just want to ask
if you can send me a link to the documentation, I will
I can't find anything like inter.send_message
what library are you using?
@potent spear mind answering this rq?
I don't have that much experience with sorting, it might be
lambda m: m.created_at instead
well i want to do who joined the guild first so
yeah, that would be fine
what else can i use like replit?
there were 2 links, as mentioned for the second time
@potent spear that worked, thank you so much.
gl hf
in scaleway is my code public?
How long will it take to register 1 slash command?
scaleway is paid? then ofc not
oh no free links?
globally? at max 1 hour
in a specified guild (by ID), sooner
i cant speak aaa!
Can we not use it until its registered
no
but just register it for one guild, so you can test it quickly, and later put it globally 🧠
I know but its still taking soo long
NVm its like not working
show your code, to prove you're actually doing it for one guild
Its only 1 help command
I removed the auto complete thing
Maybe that would do something
well, with the new api it takes like no time for even global commands to register~
no idea, I don't have any experience with v2 stuff
@potent spear this is my whole code and its not registering: https://www.toptal.com/developers/hastebin/metovazimo.py
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
It's not suggested at all to hardcode your help command
wrong decorator, wrong class
you gotta initialise that class
and since your using the commands.slash_command decorator you need to use the bot's method to add slash command manually
yup, you're trying to organize your commands in different classes, but that's not how to do it
could have used cogs.
hello guys, the bot logged in successfully but won't listen to any of these messages? why is that? maybe it is running the old version script? thank you
import discord
from discord.ext import commands
import discord.state
intents = discord.Intents.default()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"We have logged in as {client.user}")
print(f"list of client guilds: {client.guilds}")
for guild in client.guilds:
if guild.name == GUILD:
break
print(f"Guild name and ID are: {guild.name}, {guild.id}")
@client.event
async def on_message(message):
if message.content == '99!':
response = 'ss'
await message.channel.send(response)
# client.run(os.getenv('TOKEN'))
client.run(TOKEN)
is that discord.py 2.0?
yes
you need to set intents.message_content to True
is that good to use 2.0 ? or downgrade it?
depends on whether you want to use it's new features
1.7.3 doesn't have app commands and other interactions, 2.0 does
how to set it?
I can't see the official doc has a good tutorial for their 2.0
Oh now it works
I am an idiot
I used commands.slash_command instead of client.slash_command.
found a good intents intro notes thanks
@potent spear how to get the big icon infront of commands?
depends on what you think is "the big icon"
Like the bot's icon infront of the command name
you can look into the GitHub's example folder
they are noice
still don't know what you mean
also, note that since you're using 2.0, make sure to change the "stable" to "master" in the doc link since there are breaking changes
Nvm it came itself after the command was registered.
How to gives bot permission? now the bot cannot send messages in my server. Checking this bot, the setting wont save
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
print(ctx.command)``` this is my cooldown command, obviously im adding more but i need a way to GET the cooldown of the command invoked (**not** the time remaining, the actual cooldown)
I am adding a command that returns me the results of any functions (2.0 package)
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@bot.command()
async def show(str):
print(f"Showing the results of: {str}")
await exec(str)
!show guild.id --> It should show something.
But this code is not work. How to fix it?
u need to add a ctx in the args
@bot.command()
async def show(ctx, str):
print(f"Showing the results of: {str}")
await exec(str)```
try that
and if u want the message to send in the channel, do await ctx.send(eval(str))
exec() always returns None but eval() returns the output
In cogs
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, CheckFailure
class Moderation(commands.Cog):
"""Moderation commands"""
def __init__(self, bot):
self.bot = bot
@commands.command(name='kick')
@has_permissions(kick_members = True)
async def kick(self, ctx, *, member = discord.Member, reason=None):
"""kicks a member"""
if reason == None:
reason = 'no reason was provided lmao'
await ctx.guild.kick(member)
await ctx.send(f'User {member.mention} has been kicked for {reason}')
def setup(bot):
bot.add_cog(Moderation(bot))
Getting error of
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".
@oak bridge
Trying
@bot.command()
async def show(ctx, str):
print(f"Showing the results of: {str}")
await ctx.send(eval(str))
It is not working in my test
whats the error?
does anyone know?
No response
put print(str) inside the eval()
Are you trying to print the string?
im trying to print the default cooldown of the command triggered
why print()?
i dont think str will work as a variable since its an in-built function @oak bridge
eval('string') will return nothing because there was no output. just like if u make a python file and just put 'string' as the code
do eval(print(str))
what do you want to do?
they're trying to print a variable/function from inside discord
@bot.command()
async def show(ctx,arg):
print(f"Showing the results of: {str}")
await ctx.send(eval(arg))
This is not work
I want the bot could response !show client.user and return the result of client.user @slate swan
Guys tell whats wrong here :/
u didnt add print like i told u to
Can't figure it out
i got no clue
Should i send the full output?
yes
so basically something like an eval command?
bot is not defined :/
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".
try member: discord.Member instead of member = discord.Member
oh duck..
tbh id just prefer using jishaku for this
no prob it happens to everyone
!pip jishaku quite flexible and safe.
A discord.py extension including useful tools for bot development and debugging.
yeah eval() but I still can't get it running
@slate swan can you get it running?
check ur dms i replied to what u said
The amount of copyright infringement in bots is insane
Ay it worked thanks!
@client.listen()
async def on_voice_state_update(self, member: Member, before: VoiceState):
#Pings a user if they've never joined the voice chat before and aren't voice verified.
print(self)
channel = member.channel
print(channel)
Okay so I am trying to get the channel of when the user joins the channel but this just gives me when they leave the channel how do I get it to give me the ID of the channel that they join?
can u show the output of dir(self)?
!d discord.on_voice_state_update
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...
bot is only created the channel
i don't think you're allowed to ask for help with destructive code such as this
['abstractmethods', 'class', 'delattr', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'slots', 'str', 'subclasshook', '_abc_impl', '_client_status', '_copy', '_from_message', '_from_presence_update', '_get_channel', '_presence_update', '_roles', '_state', '_try_upgrade', '_update', '_update_from_message', '_update_inner_user', '_update_roles', '_user', 'activities', 'activity', 'add_roles', 'avatar', 'avatar_url', 'avatar_url_as', 'ban', 'block', 'bot', 'color', 'colour', 'create_dm', 'created_at', 'default_avatar', 'default_avatar_url', 'desktop_status', 'discriminator', 'display_name', 'dm_channel', 'edit', 'fetch_message', 'guild', 'guild_permissions', 'history', 'id', 'is_avatar_animated', 'is_blocked', 'is_friend', 'is_on_mobile', 'joined_at', 'kick', 'mention', 'mentioned_in', 'mobile_status', 'move_to', 'mutual_friends', 'mutual_guilds', 'name', 'nick', 'pending', 'permissions_in', 'pins', 'premium_since', 'profile', 'public_flags',
'raw_status', 'relationship', 'remove_friend', 'remove_roles', 'request_to_speak', 'roles', 'send', 'send_friend_request', 'status', 'system', 'top_role', 'trigger_typing', 'typing', 'unban', 'unblock', 'voice', 'web_status']
This is what it gives me for dir(self)
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
We absolutely won't help with a "nuke" command @slate swan
Lol, their profile has an "antinuke" bot link that directs you to invite this bot probably... that seems malicious lol.
lmao, what even
it's a channel nuke command, it just does py new = await channel.clone() await ctx.channel.delete() await new.send('Reset channel')
it essentially is just a channel_clear command, made one of those myself
Not today buddy...
although the word "nuke" is real sus
what
nuking servers is honestly messed up
it says antinuke
@slate swan is the code on github?
gonna regenerate my bot's token rq
Yeah what are you trying to accomplish with your command? the word nuke is kinda sus?
still sus
This code literally logs in, checks if has admin privileges, and if it does nukes. That's text book malicious...
@slate swan just rename the command to channel_clear and it'll look a lot more normal smh
why would it need to check?
it doesn't even take a guild_id, just a channel id lmao
What’s the matter here
yello mr.green person
it was not a nuke
a guy named his channel_clear command to nuke and it looks sus as hell
what he did is the safest way to delete all messages in a channel
Brad already gave the verdict, no point in arguing. Let’s move on, shall we?
Lag?
i once tried to do await channel.purge(limit=99999999999999)
laggy as hell
never gonna purge 9999999999 messages again
i saw someone else do purge 9999999999 too
sed
that's nuking
clearing a channel?
purging that many messages is nuking
clone the channel instead-
yeah that's what i do now
that's not against discord ToS though
Then what was it? Could it be used maliciously?
yes
well, the person would have to be an administrator to ruin his own server
yeah the admin check is sus
so he could do the same as this without the bot
just do @commands.command(manage_channels=True)
Nope
Sorry sir
he could do many worse things without the bot
why can't I just send messages normally
idk
bro what
he did an admin check, no?
Not really unique but I’m still proud of it: being able to give infractions on discord using my bot, and being able to delete them on the website 😊
How to add perms to slash commands?
advice for y'all just do py @bot.command() @commands.has_permissions(manage_channels=True) async def channel_clear(ctx): new = await ctx.channel.clone() await ctx.channel.delete() await new.send(f'{ctx.author.mention} channel cleared!')
don't use nuking anywhere
this is literally the same
yeah just the name
One of the only things you can do there
hehe right
it would still look weird
it would print many times in some days
cuz on_ready sucks
did u get reaction perms with the helpers role
or the events team
What's the difference between on_message as an event and as a listener
other than go to all servers you're in and dm every member saying "Hello, I'm now online!"
event uses setattribute on the client's on_message
meaning it completely overwrites the default on_message
Quite big actually. If you’re not careful with on message event, it can block your commands from working
the default on_message handles commands, so if you overwrite it, you'd have to handle them yourself
This is because on message gets called before all command handlers
I want to make a riddle command that asks many riddles and gets many answers at the same time
Can I use on_message for that
on_socket_event_recieve 👀
that too
Where to learn python for discord bot coding?
actually there are plenty that get called before command handlers
But on message is an interesting case
any where but lucas
What
Or any YouTube tutorials
check the pins, there are quite a few good tutorials
word of advise before you start: do NOT watch YouTube tutorials
mmm I would use a bool bot variable that I would turn on once using a command, then get the messages in a list while that var is True
Is this python or js
If message content ===
🥴
JavaScript
it's a way
Strict equality operator
Ok then js better bcz ez
I will twitter you
Yes
I don't even have twitter
flashbacks to that time I made some bot tutorial videos 😳
Good thing you don’t anymore
Can wait_for be used simultaneously with many members

we here at discord bots collectively despise YouTube tutorials
damn, i just realized i kept my p out of that little underwear hole in my shorts this whole time, gtg
i remade dank memer
Like I ask many questions and I move to the next question if no one answers in 1min or someone answers correctly
👀
dope name ik
i smell copyright infringement
EW MY VOICE EW EW EW
@vcokltfre.event
async def on_dpy_update(update):
await vcokltfre.make_new_video(discord.default, update)
me too
I still need to spend a good few days updating my text-based tutorial
@tasks.loop(seconds=1)
async def tutorial():
new_tutorial()
tutorial.start()```
I can ping any role
hm
I decided for some idiotic reason to re-add discord.py so that's gonna be fun since it handles app commands totally differently
exit()
from sys import exit as end_it_all
end_it_all()```
it's fun doing app commands in dpy
@heady sluice
wtf
import sys
sys.exit('life')
while True:
discord()```
does this work with roles
can I ping a role for that I don't have permissions to ping
@sick birch sup
no
Add a & after the @
this is trippy
might wanna get that checked out
It will look like you pinged a role but you didnt
Ur part of <@&787816728474288181>
breathe out as hard as u can but while holding ur breath
ur lungs will feel like they are collapsing
It didn't ping btw
what's trippier is putting some text ||||...|||| https://somelink and it doesn't show the link but embeds
its 255 spoilers i think
or 198
I hope that doesn’t ping the events team
It doesnt
If you do this and it actually bursts you can haemorrhage and die
It didn't ping u sooo
so like... dont
I can’t tell because you pinged me in the message
yeah ill stop my head hurts
whats the point of living if ur just gonna die anyway
<@&787816728474288181> here
I see
in on_connect what objects are available?
dir() will tell u
it wont
It will
None, I believe
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__', '_base_executable', '_clear_type_cache', '_current_exceptions', '_current_frames', '_deactivate_opcache', '_debugmallocstats', '_framework', '_getframe', '_git', '_xoptions', 'abiflags', 'addaudithook', 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'hash_info', 'hexversion', 'implementation
... (truncated - too long)
Full output: https://paste.pythondiscord.com/vekaxoqero.txt?noredirect
hm
@rocky hornet
it shows all functions and objects
stop, you're not useful
u did ask
i asked what can i use while being inside on_connect
He atleast tried to help you
What if I add on_message as an event and also as a listener in a cog, will the on_message listener be fired when I run the command
and just do what i said
Yes
How does it work is what I'm trying to understand
listeners will always be
Basically yeah
you clearly dont understand im asking in context of discord bot, which doesnt load every guild, every member, everything right on connect, dont you?
Because I'm tryint to make a command that asks a question and receive answers from many
I didn't even reply to u I replied to @digital mason
yeah wrong reply
lmao

discord itself sucks, they havent changed the ui in ages
uh
in their tos, they say that they offer their product as is, meaning that you agree to whatever they offer
Generally, like on ready, it’s best not to do anything inside on connect except maybe printing to console that you connected
Kinda sucks
I hope that answers your question
everything is availabe, nothing specifically, you just shouldnt do anything in it other than print statements
thank you very much
someone give me ideas im bored as
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: could not find open space for item
Is this because I'm adding too many items in the Modal?
the docs are vague on this topic. it just says that on_connect isnt the same as the client being fully prepared, and refer to on_ready. so whats the difference?
On connect happens when you actually connect to the websocket. On ready happens after your clients cache is ready
it also says that warnings in on_ready apply to on_connect too
but usually theyll happen very close to each other
I see
Which is why me and Ashley mentioned not to do anything there except printing
Im just trying to find out where it is best to start interactive REPL session
so i'd do that in on_ready when everything is ready
An interactive repl session? Can I get more context?
a separate thread that constantly asks for console input
it has different commands like send a message to channel
Do I need a cog to add a listener
No
How
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external
event listener. Basically this allows you to listen to multiple
events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
@bot.listen()
...
I see, but can I use it for a command ? Like whenever someone answers my question I get the reply ?
That’s more suited towards wait for
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
Bot is a subclass of Client, so ofc u can access this from bot instance
Does discord form allow only 5 items?
I have to set a timeout for wait_for but I also need a timeout so that if no one answers in a given time it should move to the next question
Right
@sick birch could you spawn docs for that setup hook thingy?
So use the timeout
But many will be using the bot not just one
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before
it has connected to the Websocket, overwrite this coroutine...

here you are
yeah seems its discord.py exclusive
How does setup_hook work
personally I’m not sure exactly when it gets called
but it’s async and only called once
Anyone help me at making a image search command pls
Me not getting good tutorial on Google
I tried with a while loop that keeps asking for user input, and breaks when time between before the loop and current time has elapsed
its called before connect though
I think it’s right before login
But wait_for blocked the bot so it kept waiting for a message
wait for is not blocking
its after login but before connect
it blocked the bot
That’s not possible if you’re doing it right
it blocks the function until it gets the event, not your complete bot.
Yes blocks the function
i remember asking for help in this channel once on how to get an attachment and read the contents, no one gave me a concise answer, so if anyone is wondering - (await attachment.read()).decode() I hold my grudges
For example if the bot should move to another question after no one answers in 2 minutes, wait_for keeps waiting for someone to answer
Did you pass in a timeout?
await read() already gives you the contents
it gives bytes
I guess yes
at the time, i didn't understand "bytes", and no one explained how to get a string from it
you first need to make sure this is a text file
hi guys..
bytes and strings are notoriously difficult to work with
You work with strings in C or rust and you know why
strings in C 🤔
I would rather watch discord bot YouTube tutorials than work with strings in C
but C doesnt have strings
I know
char arrays are close
that’s why it’s such a pain
Rust it’s more of an encoding issue
me who doesn't know C 🍿
@sick birch you better think of C as an abstraction over assembly, and it suddenly makes a whole lot more sense
lol
!pypi assembly
Assembly is a pythonic object-oriented, mid stack, batteries included framework built on Flask, that adds structure to your Flask application, and group your routes by class.Assembly allows developers to build web applications in much the same way they would build any other object-oriented Python program.Assembly Makes Flask Great Again!
uh~
eh
do !pypi binary too
terrible naming scheme
!pypi asm
!pypi binary
that was a joke comment
The problem with timeout is that it doesnt give time to answer, is there another solution that keeps waiting for messages like on_message does
okay im gonna fix dis
!pip brackets this looks like a fine Library lmao
Anyways ot
LETS GO
Whut
HELL YEAH
while True:
try:
new_message = await bot.wait_for(event="on_message", timeout=69, check=lambda m: m.author == ctx.author and m.channel == ctx.channel)
except asyncio.exceptions.TimeoutError:
# do extra checks here
if checks_not_met: continue
else: break
else:
await ctx.send('timed out')
break```
I did that
But how to make sure that the while breaks if no one answers after 2 minutes

while True:
try: await wait_for("event", timeout = 120)
except: break
🔫 now do it on one line
???
Oh wait
they want to keep recording an event until someone doesn't respond within 2 minutes.
my logic is flawed
bare except :(
well, I didn't mention wait_for as bot.wait_for either, and the event name too xD
BaseException lookin' real hot from here
What is Key Metadata?
did you do something with your pyproject.toml?
I didn't even touch that file
hey guys, is there a way to see what permissions a user has in a guild?
member.permissions
or close to that :)
how would I get the list of users who joined the server before x date?
ah ok, so whats the best way to get the member object from a user in a guild. should i just iterate through the guilds members?
nope
member.guild_permissions
or for specific channel
channel.permissions_for(member)
guild.getch_member
i just realized
name getch is get and fetch combined
oh thats useful!
You’re gonna have to filter it out yourself
as in?
@sick birch can you help me with some code?
Use .created_at along with filter()
Sure, what’s up?
okay thank you
So I'm not sure what's wrong
yeesh, heard of copy paste ever?
i can't read that with my bat eyesight
That's on my school laptop
can't help if i can't see the question or the error
Discord is block on it
rip
last question hwo would I compare the datetime.datetime object from joined_at with a date?
hello, ive been trying to make it so when a mention is sent it updates the channel for that user and sends an embed into a specific channel, however, it wont send the embed to the channel. I don't get any errors...```py
elif message.mentions:
user = message.mentions[0]
await message.channel.set_permissions(user, read_messages=True, send_messages=True, embed_links=True, attatch_files=True)
await message.reply(f"{user.mention}", embed=discord.Embed(description=f'{user.mention} was added to the ticket {message.channel.mention}', color=0x57f287))
mycursor.execute(f"SELECT * FROM t_info WHERE channelID = {message.channel.id}")
for o in mycursor:
req_embed = discord.Embed(title="Middleman Request!", description=f"<@{o[0]}> is looking for a middleman!\nOther Trader: {user.mention}\nTrade: {o[3]}", color=0xe15252)
guild=bot.get_guild(901481491337465928)
join_msg=guild.get_channel(975083898365157376)
await join_msg.send("<@&925444830480453644>", embed=req_embed)
Easiest way would be to use .timestamp()
how to create a channel under a specific category?
Since those are integers you can do regular comparison operators
not sure if this makes sense but if a user sends just my command prefix can I make that execute a function?
like run my help command
Don’t believe so
!d discord.CategoryChannel
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments...
guys can anyone help me even
help
!d discord.CategoryChannel.create_text_channel @slate swan
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
enable intents in the dev portal
and be more patient
be patient stop messaging in DMs
okay
stop spamming
sorry
very very sorry i apolizise
go to your application on that link and enable the intents you're requesting in code
not a problem
it doesn't
okk
there's no way the token resets unless you do it
se a production WSGI server instead.
- Debug mode: off
- Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
Traceback (most recent call last):
File "main.py", line 336, in <module>
bot.run(token)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result() - Serving Flask app "" (lazy loading)
- Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead. - Debug mode: off
- Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
Traceback (most recent call last):
File "main.py", line 336, in <module>
bot.run(token)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
return future.result()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
await self.start(*args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
await self.login(*args, bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 216, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
thsi error came
help me
@heady sluice
yep
yikes
yes
Develop locally, host on a vps.
how to write unit tests for discord bots?
how to host a bot on visual studio code
lol what
IDEs != hosts
localhost
local host?
hosts.txt
Hosting it locally.
python -m bot
eh unit test?
?
I'm trying to make it so that when a used ID is sent it updates the perms for that member and sends a message, then i want it to send an embed in a specific channel, BUT, it doesn't seem to work and i'm not sure how to resolve it..py elif message.mentions: db = mysql.connector.connect( host="", user="", passwd="", database="") mycursor = db.cursor() user = message.mentions[0] await message.channel.set_permissions(user, read_messages=True, send_messages=True, embed_links=True, attatch_files=True) await message.reply(f"{user.mention}", embed=discord.Embed(description=f'***{user.mention} was added to the ticket {message.channel.mention}***', color=0x57f287)) print(1) mycursor.execute(f"SELECT * FROM t_info WHERE channelID = {message.channel.id}") print(2) for o in mycursor: print(3) req_embed = discord.Embed(title="Middleman Request!", description=f"**Trade:** {o[3]}", color=0xe15252) guild=bot.get_guild(901481491337465928) join_msg=guild.get_channel(975083898365157376) await join_msg.send("<@&925444830480453644>", embed=req_embed)
will it host for 24/7?
if u dont turn off the system, yes
Depends how long your pc is on
Why do you need a host if the bot isn't finished..?
in any case.. hosting it locally.. would need your system to be ON lmao
if you want a free hosting for a small bot, railway.app is decent
bot is finished
i just need it to be host
maybe #965291480992321536 is for u
and again.. free hosts gonna have their limitations
ppl usually use repl, heroku afaik
for free, but again ^^^
only in terms of memory or cpu i guess
any ideas?
how to get a project on github?
well in duration too
this is a channel about discord bots
heroku has limited dyno hours
wdym by 'get'?
right, it does some restarts
A lot more.
yea i want my bot to be on github
no, i mean limited dyno hours, not restart thing
can't you just make two apps for the same code
just publish it?
soi can host it from railway.app
and start the other when one's hours are gone
how tho?
idk, my bot runs 24/7 on heroku
bro.. 💀 u want me to teach u github?
💀
heroku uses github
@quaint epoch
it doesnt
o
tho they are trying to fix it.. but for now, nope
yes
I didn't know
for sexurity
mmmmmmmmm
close enough
that's what she said
so for now.. one have to use Heroku CLI
yeah
anyone?
💀 idk.. just look up on youtube or whatever.. whateveru feel comofrtable
this was in reply to my msg btw.. just telling
k
are you creation a db connection inside a command?
Traceback (most recent call last): File "main.py", line 475, in <module> client.run(os.getenv('TOKEN')) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 708, in run return future.result() File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 687, in runner await self.start(*args, **kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 650, in start await self.login(*args, bot=bot) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 499, in login await self.http.static_login(token.strip(), bot=bot) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 291, in static_login data = await self.request(Route('GET', '/users/@me')) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 209, in request raise HTTPException(r, data) discord.errors.HTTPException: 429 Too Many Requests (error code: 0): You are being blocked from accessing our API temporarily due to exceeding our rate limits frequently. Please read our docs at https://discord.com/developers/docs/topics/rate-limits to prevent this moving forward
the bot is not running
bruh
btw how to run the thing on visual studio code (python)
huh?
it is self explanantory, you're blocked
get off replit
see your bot page
how to run
...
wdym blocked
💀 if file is in the same directly.. with name main.py then command is ```py
python main.py
your did something that crossed discord's rate-limit
Most likely repl.it host
its tdfhgfdswdsa-2 if you didnt catch it
it's like nasa naming planets
owo.. hosting on repl crosses discord's rate limit?.. just asking.. 😐
any idea what it can be?
dood!
cuz it was running fine earlier
its asus naming monitors
uhm.. well check your bot page on develoepr portal..
it hsould have something imo
No it's just that you share an ip with multiple people.
🤔 i see
what do you mean?
replit
cd Desktop\t and keep pressing Tab.
he's saying.. are u connecting to DB inside the command function?
how do people even find replit
PS C:\Users\DELL\Desktop\tdfhgfdswedsa-2> python main.py
Program 'python.exe' failed to run: The application cannot be started because it is currently updatingAt line:1 char:1
- python main.py
-
At line:1 char:1
- python main.py
-
+ CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException + FullyQualifiedErrorId : NativeCommandFailed
PS C:\Users\DELL\Desktop\tdfhgfdswedsa-2> main.py
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- main.py
-
+ CategoryInfo : ObjectNotFound: (main.py:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
this error comming
More like repelit 
on start sometimes
i use replit, i need the bot to run urgently
what should I do?
called it
that's a bad practice.. better subclass commands.Bot & connect to it on its init method only
that's my imo btw..
help
Something like kill 1 in the console should reset your ip.
i prefer doing it the way im doing now
ok
Nothing you can do except stop using replit
or utilize dependency inversion pattern and pass the connection to init
yeah.. at the end.. we're coming to init, lmao
that's what i mean, subclass the bot. it's the most effective way when dealing with dbs in discord bots
ok then pass it to __new__
💀
💀 your choice bro
so can you help me with the actual code i sent?
actually, use an async library.
!pip aiomysql in your case
^ +1
I dislike these drivers
if you use 2.0, you can use the setup_hook to setup your connection.
ok
maybe just me tho
just you
Look into an ORM
its here
whats the point
init is better
you may use db before starting the bot
no. init wont work for async libraries.
so why do you have to subclass for that
setup_hook is an coroutine, thats the point

eh you dont really need to subclass to use setup_hook
bot = commands.Bot()
async def my_func(bot):
...
bot.setup_hook = my_func
in asyncpg, connecting to a db isn't async iirc, just the calls
I could connect to the db with just
bot.db = connectshit
idk, libraries like aiosqlite use coroutines for that
after bot = commands.Bot
no, it is
well I definitely didn't have to await
you will have to
or did I do it in asyncio.run?
anyone???
yeah probably
How to do the right check? If the verification level on the server is high, then ...
🍿
well, youre making multiple connections ( a connection each time a message i sent and someone is mentioned in it ), so yea you are messed up already.
and you need to use cursor.fetchone()/.fetchall() to get the selected data, you cannot loop on the cursor.
!d discord.Guild.verification_level
The guild’s verification level.
just use == "high" um?
ive already tried that and it doesnt work
idk then
o
i use cogs and wanna timeout a user how do i do it?
code:
# timeout user
time = humanfriendly.parse_timespan(time) # convert time to seconds
await member.timeout_for(time, reason)```
whats wrong? how do i fix it?
error
```error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: timeout_for() takes 2 positional arguments but 3 were given```
how do i timeout them?
what library>?
hello, so what would be the diff between async def bla(something = None) and async def bla(something)
the argument something wouldnt be required and its default value is None
!e
def a(arg):
print(1)
a()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 3, in <module>
003 | TypeError: a() missing 1 required positional argument: 'arg'
!e
def a(arg = None):
print(1)
a()
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1
gotcha
pycord
reason is a kwarg ```py
timeout user
time = humanfriendly.parse_timespan(time) # convert time to seconds
await member.timeout_for(time, reason=reason)```
can someone help me in a few mins?
Ask away
wait ima be back
means?
@slate swan i tried this
i just send the code...
oh sorry lost
what about this warn?
use datetime timedelta
i use datetime
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
U can use this
@frigid apex
is this ok?
don't name all var same
it works now
Nice
i wanna learn nural networks an more ai stuff how can i start?
https://paste.pythondiscord.com/ozojeludib can someone help me?
Hi ash
oh sorry wrong channel
Hi Sparky
My discord is glitched
it's not showing today at its showing 20 may....
What's the issue
Uh
reload it, ease
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
ok
Did u removed those ```py
i have quite alot so ill send the code in parts
Ye sure
first this ig
First indent here we go
Match that else
ok
Imagine
it still shows as an error smh
@warped mirage did u copied code from somewhere
Ye buz ur last if statement
my mate borrowed me some parts but if that counts i guess
i lined them up
Show
if level < 5:
xp = random.randint(1, 3)
async with client.db.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,)) as cursor:
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp = random.randint(1, 3)
async with client.db.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,)) as cursor:
if xp >= 100:
level += 1
async with client.db.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,)) as cursor:
async with client.db.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,)) as cursor:
await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
await client.db.commit()
``` this is currently what i have
then code from level += 1 errors out, indents it too
Ss
xD
yes , i use to be good , but i recently came back and idk indents give me a breakdown
congratulations, you just said a lie
nah
indents is my only problem i need to get better at
Huh
Coding is pretty much riding a bike.
Cycle*
so what now xd
ur american?
!indention
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
No
I realized this after I said it lol
Lol
looking much better
Bro
bruh xd
!d discord.Guild.premium_boosts
No documentation found for the requested symbol.
these will error
cycle* cuz u can code when ur small too
Uh
hunter enters
I am out
what do i do then?
Lmao
What does size have to matter with coding..?
async with something.something() as smth:
await smth.do_something()
thats how you use those async with statements mostly
!d discord.Guild.premium_subscription_count @slate swan
The number of “boosts” this guild currently has.
I mean kids can't ride on bike
Smh can't Danny name this as simple as boosts
Bruh
No wait
Lol
guild.premium_subscription_count
lmao im so pissed xD
Danny was trying to be creative
Discord API
🏃 🚪
await client.db.execute()
easy as that, why would you redefine whats already been defined as needed
still.......an alias helps
Agreed
So instead of async with it’s just await ?
Hey
correct
yes...
So I made wordle in python, and I think it would be cool if I added it to discord, too
Ok
Ok
i just dont know how lol
Idk how to like make a command, so when you run it, it will wait for ur response, edit a specific message that it will send at the start of the game, and continue doing so
Do u know basics of d. Py
not really
I mean if you know a guide that explains what I'll need to make wordle in discord, I'll be down to read it
Ash do be writing an essay
Ye
Ashley is typing...
Tutorial one
It showed that u were typing since the last 5 min or smth
I wasnt-
😭
u copied the text
hm
okimii's eyes are scary
Ye
now I got a creepy picture
Ash the snail typer 🐌
Discord still shows as typing if u don't type smth, for a min or two or if u leave a char in the textbox
It's only 10 sec but
8 - 15 seconds
indents are just to separate through code blocks
its really that easy to explain
shows for like a good minute for me weird
Prolly I am wrong but 🤷♀️
How indents are actually used are if you want a piece of code to function under one specific condition (not if-else)
if condition: <------------
print("yes") |
print("whatever") |
else: #this will error as | is not inside another conditional and is a standalone conditional, this `else` errors out because an `else` cannot be used without an `if` and as you can see that you are embedding an `else` inside an `if` which further does not contain an `if` inside the root `if` and only an `else` this is the reason why your code was erroring out with indent errors
...
async with something() as smth:
''' Here you will have to perform a task or `pass` or use an Ellipsis for this temporary open statement '''
'''else anything you write under it will error out '''
''' For example '''
async with something() as smth:
if new_condition:
... #this errors out, refer to the above message
Refer to this -> #discord-bots message
(apologies for the ghost ping earlier, I had to correct my shitty grammar 😔)
🥱
anyways, I know, someone will find a mistake out of this too, you're welcome
this message makes me wanna cringe
yo i added await for every execution and gives me 20 errors
im so damn confused ......
Syntax error
How do you actually expect us to help you with indents 😭
Rip 5 min typn
Sad
normal , "LEFT" , "RIGHT" )
yeah i know im a slow typer....
...?
Hello, well, as you know, when the bot turns off and on, it no longer responds to the buttons that were sent before it was turned off, and we have to send new buttons. How can I make it start responding to buttons that were made before it was turned off?
use persistent views
Actually , im using py-cord
does this work for pycord too ?
Yea
Backspace, spacebar*
nah im serious lol
https://paste.pythondiscord.com/ayomamuwed i need help check this lol
hiy a
If you do not understand what exactly I am writing, do not even try to say anything, do not provoke me to insults.
how to put a class for buttons in a file where you already have a class with cog. Please read the message above!!!
