#discord-bots
1 messages · Page 29 of 1
And see my code
Don’t use list for 1 integer unless there’s multiple owners
@client.event
async def is_owner(message):
owners = [493928382, 59293858]
if message.author.id in owners:
return owners
well, bot.http.add_role(g_id, u_id, r_id) 
Is it possible to make a personal disc bot that tracks the messages that pings me?
event?
an esoteric way to override the is_owner method
was referencing generally not just about adding and removing
yes ofcourse it is, given that the bot needs to be in server ure getting pinged
not sure why you replied to my message about roles, but even then the performance impact between an integer and a list of one int is so negligible you wouldnt notice
yeah i get that but you can just pass owner_ids kwarg in Bot constructor for the same
thats what i said too
demonstration: ```sh
py -m timeit -r 5 -n 1000000 -s "n = 966318461582213121" "n == n"
1000000 loops, best of 5: 12.9 nsec per loop
py -m timeit -r 5 -n 1000000 -s "n = [966318461582213121]" "966318461582213121 in n"
1000000 loops, best of 5: 14.3 nsec per loop```
Oh, I see now. Sorry
Thanks, I got it. 🙂
hey i am making a currency system with discord.py and json
i get this json error json.decoder.JSONDecodeError : Expecting value: line 1 column 1 (char 0)
uhmm the meme cmd is kind of late responding to the
command
is there anything to fix this delay?
You should be using aiohttp instead of requests
Or another async http client
As for the delay, is the meme api slow to respond?
Don't use json as a database (very easy)
I mean why not if it is just gonna be a small project
Sqlite is good for small projects
@commands.has_permissions(warn_members=True)
@client.command()
async def warn(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "No reason provided"
if member.warns == 3:
member.ban
await member.warn()
warn_messages = [
f"Pichu used charm to warn", "Pikachu used thunder shock to warn",
"Raichu used walt switch to warn",
"Squirtle used water gun to warn",
"Wartorle used rapid spin to warn",
"Blastoise used skull bash to warn",
"Bulbasaur used leaf blow to warn",
"Venusaur used solar beam to warn",
"Charmander used Flame thrower to warn",
"Charmeleon used metal claw to warn",
"Charizard used inferno to warn"
]
await ctx.send(f'{random.choice(warn_messages) + " " + (member.mention)}')
keep_alive()
client.run(TOKEN)
error - Traceback (most recent call last):
File "main.py", line 68, in <module>
@commands.has_permissions(warn_members=True)
File "/home/runner/ChatBot-1/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1779, in has_permissions
raise TypeError('Invalid permission(s): %s' % (', '.join(invalid)))
TypeError: Invalid permission(s): warn_members
KeyboardInterrupt
anyone here?
Basically this ig
we cant warn members?
Well that doesn't exist since discord doesn't have any concept of warns
we cant do warns dpy?
Never said that
then?
I said discord doesn't have any built-in warn system
As such, there is no permission called warn_members
hm so what to do?
Make some system of your own with db
You could use some other permission
k
like kick_members
alr used
and btw can we do
await member.ban
smth like this?
Check the doc for discord.Member and see
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
you got ratelimited from the discord api
what does that mean
go to shell type kill 1
ok
how did that happen and how do I prevent it
prevent it by not using replit
epic bruh moment
and making less requests in your bot, maybe you're the reason for the ratelimit idk
- not use replit
- control the amount of requests (if replit, this does not matter)
Optional: kiss asher

umm no thank you already feeling awful
well I use replits always on to keep it alive
😔 relatable, even I got a cold
that's why you dont use it to use it
What if u r a discord dev 👀
And have the internal test build
eh
remove one .datetime
Not sure if it's more suited for here, or #databases will ask it here first:
So, I'm trying to insert some values into my *.db folder, but for some reason it's using my "your_description" argument as column. So if I lets say use /register your_description="hello" it tries to access "hello" as column from my table. I'm not sure how to fix that
@bot.slash_command(description="Database testing.")
async def register(inter, your_description: str):
Cursor.execute(f"select * from userregistration where userid='{inter.author.id}'")
if str(Cursor.fetchall()) == "[]":
Cursor.execute(f"INSERT INTO userregistration (userid, timestamp, description) VALUES({inter.author.id}, {round(datetime.datetime.utcnow().timestamp())}, {your_description});")
Connection.commit()
await inter.response.send_message("Successfully registered! Please use '/profile' to view your profile.")
return await inter.response.send_message("You are already registered.")
is it too many of these
thats a mess
is that why my bot god ratelimited
no that's the uptimerobot
oh well I don't use that anymore
It is 😔
Just trying to get it to work
I use replit always on
how the hell do you know its uptimerobot asher🗿
why did I get ratelimited tho
even if that, a bot doesn't have a warn_members permission
!tag itworks
seen before in this channel
bruh always forget(
imagine
pass_context 💀
ratelimits are made to prevent the attacks like ddosing/flooding a service
don't use f string with SQL and u can just do if not cursor.fetchall()
and i don't think u need the ;
so ratelimits happen to everyone?
this hasnt happened to me before
How would I go about inserting the author id, and the timestamp? Can I simply use it without f strings, or would I need to store it in a variable?
no its an implementation in this case, a per discord API endpoint
also make sure u are using an async db
async driver*
check examples on internet
explain in stupid people terms
depends on what db u are using coz the they have slightly diff syntax
life too short for technical bs just explain in human terms :kek:
imagine using cursor.fetchall 😔 why dont people just
d = await (await cursor.execute("SELECT * FROM table")).fetchall()

Sqlite3, as far as I understood it I will need to have the variables saved as tuple then?
could someone show me a example code of a slash command please
yeah use aiosqlite tho
will this work for mysql?
similar syntax
it should, never worked with it
aiomysql
What are the advantages?
runs changing queries
await cursor.execute(f"select * from userregistration where userid=?" , (inter.author.id, ))
OR
await cursor.execute(f"select * from userregistration where userid=%s" , (inter.author.id, ))
ITS ASYNC
why does everyone say explain in "stupid terms" i already am😭 , im joking, theres buckets that handle requests from a client which when depleted in a certain time frame discords API wont handle any more requests as you already have depleted the bucket which ratelimits are dynamic per endpoint of discords REST API
spoiler: no one knows what does async mean
I'm aware of that, but how would it significally make a change
it runs on the event loop and passes tasks to the event loop so the event loop manages and achives concurrency
multiple people can use the command at once
bruh I'm starting to want even more to switch from mysql to asyncpg
but that'll be hard(
it has those pools(
you dont like swimming?
(I can't swim)
Can I call from Python to async without async?
sad
!d asyncio.run
asyncio.run(coro, *, debug=False)```
Execute the [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) *coro* and return the result.
This function runs the passed coroutine, taking care of managing the asyncio event loop, *finalizing asynchronous generators*, and closing the threadpool.
This function cannot be called when another asyncio event loop is running in the same thread.
If *debug* is `True`, the event loop will be run in debug mode.
This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.
Example...
yeah))
it depends
"Asyncio.run" i can't use this right now. Is there any other way?
What are you trying to do?
why you can't?
you can get the event loop and schedule a task
Call an async function inside a normal one?
the only reason why you couldnt is because theres already an event loop created/defined
I think ik why I got ratelimited
Cool
⭐shared internet protocols⭐
my bot has multiple @bot.listen()
o
thats a dpy abstraction, so parsed payloads get passed to certain namespaces/functions
I spent 9 minutes googling every word you said in that sentence and I still don't get what you meant
@commands.slash_command(description="Purges an amount of messages from the text channel")
async def clear(self, ctx, amount : int):
await ctx.channel.purge(limit=int(amount + 1))
How do I remove "Application did not respond" Error to this command?
respond to the interaction e.g send an ephemeral message
respond in someway, ephemeral probably is best

Alright coolio, thanks guys
Also, does disnake reload=True work for you guys>?
Its stopped working for me once i upgraded disnake via pip
ok idc abuut the details of all this api ratelimiting stuff
what permissions must user have to timeout other users?
the fix to getting api ratelimited is typing kill 1 in the shell
iirc manage_members
thx
is there any way to make it automatically do this
youre welcome my fren
you can use os.system
🫂
yes im familiar with that
some people just have error handlers and use os.system so python kills the container
❤️
Ok
and then they run another script that runs the main one its a mess lol
I guess this is the most powerful..
yes
i heard of that before
someone in replit discord told me to do that
they said, "ALL THE PINGERS I LINKED WORK, THERE IS AN ERROR IN YOUR CODE"
there was no error at all
any shortcut for changing 100000 to 1,00,000
the pingers were just trash
!e
print(f"{100000:,}")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
100,000
theyre only possible in f strings lol
what the actuall hell
got it thaanks
python nether
✌️
what does that mean
hmm
got it thanks
like my approch will be
x = random.randint(1,2)
if x==1:
#do this
else :
#do this
any other option ?
@vocal snow
i this good ?
!e
print(f"{100000000:,}")
@swift pumice :white_check_mark: Your 3.11 eval job has completed with return code 0.
100,000,000
you can use match case trees or dicts
#bot-commands
any link so i can read it more !!
ok
theyre just named like trees but its just there structure lol
o thanks
will this type of reconects affect my asyncio.sleep fun ?
or cooldown ?
ands whats websocket ?
nah it shouldnt
a websocket is basically a socket for the web/TCP connection that connects with a handshake, when it connects it uses an HTTP request which then when the connection is establish you can send binary packets from server to client and vice versa due to bidirectional communication
confirm = await ctx.respond('Yes or No?')
response = await self.client.wait_for('message', check=lambda message:message.author == ctx.author and message.channel.id == ctx.channel.id, timeout=60.0)
if response.content.lower() not in ('yes', 'y', 'yup', 'sure', 'ok'):
await ctx.respond('No')
else:
await ctx.defer()
#Long request here
await confirm.edit_original_message('Done')
How do i properly defer after the user has responded with 'yes'? The request takes longer than 3 minutes so the response doesnt send.
Is this the way to check if the ctx.author is a specified user? py if ctx.author is "Test#1234"?
its better to check the users snowflake/id
right now you're checking if a Member or User object is a string which would always be false
Can I pass some datetime into until param in timeout func so it will be not 3 mins or hour or 24 hours like those options, so like can I have my own amount of time to timeout?
because I just did that and it didn't work
is there a tutorial?
its a simple if statement there wouldnt be any
For what are you checking if a context's author is a certain user?
is a string, not == 💀
iirc you pass timedelta oh and the permission to timeout a member is moderate_members lol, just remembered
but it says that also datetime.datetime is possible
mhm well im not sure, ive only worked with disnakes timeout lol😅
Remember you should be working with UTC aware datetime objects
ofc
So maybe try discord.utils.utcnow() + datetime.timedelta(seconds=20)
Right
Cause I have datetime object, do I format it into timedelta?
From where do you get the datetime object?
nvm im just dumbass
why?
should I use this function? discord.Client.fetch_user
you can compare ints?
if ctx.author.id == 0000000000:
...
Any ideas?
argument naming 
confirm is a Message, you should use edit, not edit_original_message
anyways
isn't defer used at the start of the command
its used to refer interactions
InteractionResponse maybe
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...

hehe
typically used when the interaction is acknowledged and a secondary action will be done later
like waiting for a message and sending one later
?
hey I see you, lemme wait for a message which you don't even know is happening, and then you get an answer
not exactly, hence the word "acknowledged" you know it exists but you respond later on
Yeah but can i defer after the confirmation?
I tried at the start of the command and it doesnt work
@bot.command()
async def w(ctx, member):
user = ctx.message.author
role = discord.utils.get(ctx.guild.roles, name="WHITELISTED")
if role in user.role:
await ctx.send(f"{user.mention} Already has the whitelist!")
else:
await user.add_roles(role)
await ctx.send(f"{user.mention} is now whitelisted!")
Does any one know why is not checking properly?
if role in user.roles:
but why is user always the author
use member
if role in member.roles:
#member is already whitelisted
it would raise an attribute error
and you can hse ctx.author over getting the message instance and using its attr
#databases can someone help?
i think you ment in?
Please don’t cross post here. Wait for someone to come along and help
oh got it but and will work op right ? mem_total > 1001 anda mem_total <10000
can you help?
No, but just refrain from xposting
so you wont help me?
okmi
Not that I won’t, but that I can’t
Just let someone help you, no need to ask in an unrelated channel
it's related
because it's sql in a discord bot
Databases and discord bots are different channels, don’t ask for help on the other
It’s also off topic for this channel
#databases would be better for mysql
even though you are using it for dpy
you need answers related directly to databases
fair enough
no
this channel is especially for discord API wrappers, nothing else
and it's used in a wrong way so many times
Nv
this channel is for bot development, #965291516031549500 is for discord API wrappers written in python lol
bot development in discord API wrappers
bot development with discord API wrappers written in python*
rookie numbers mine sends 13
why does it tho
❓
why does it send 4 messages when u say a commasnd
you can have multiple instances of your bot running
the more the muscle the more messages sent
for pycharm how can i fix it
Close all the pycharm terminal windows
🤪
what do i do
nsfw
no
yes
ignore my code
ok
fine someone wantedd me to make it
async def cmd(message) 💀
probably close a running window
There is a red box on the top right corner, click on it and terminate all processes and try running your bot
ok
At least it doesn't make you write lua, lol
that didngt help
that didnt help
bruh google translator translates stroke to russian two different names: to pet and insult (heart attack)
do you have an on_message
no
the definition gives you a whole stroke💀 😭
now in this sentce it translates it like "hatch"
google translator is complete trash
why are you translating every sentence
😭
no i dont
I didn't know the meaning of word stroke and tried to translate it but translator gave me all those stupid answers
but of the context ig it's heart attack..
it's when heart go brrrr
but I have no heart
Welp, Oki dead
Oh wait, no it appeared after I saw okimii

bro what
hey i dont have a on_message
that sucks
maybe I should add breaking changes here
make Changed to Changes
oh yeah
2021 💀
LMAO why not
good tz with diff in 1 year
guys how can i stop multiple instances and some people are asking do i have an on_messasge why?
😭
omg I guess I had enough strokes for today
ngl that day format reminded me of a socket endpoint for some reason
Is that funny or sad that so fortunate that I have problems with heart? 🥲
kinda funny
yeah...

bruh I wanted to tell joke about myself but it was too bad... ig...
it probably wouldve been cheesy
Wait but changes is like the whole thing in one: added, removed, edited, e.t.c.
ooh but then I can use edited
well yeah, it probably should be a resumed version of the whole paragraph so it should be at the top
ok banana, anyways i want that my bot changes his pfp every idk minutes, what line can i not cross like i dont want to get banned
do you guys understand what i mean?
@slate swan what's rate limit for profile changes
it's definitely not big
I think it's 1 profile change every 10 minutes
oof im not sure on that iirc its something like 1/10m
that's what I thought too
(edited) 👁️👁️
I forgot to write the number
before
mhmmm🤔
why does this not work
i dont get any error but it still isnt working
!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.
you almost had it
you send the message like
await ctx.send("hello")
but you wanna edit it later so you save it like
message = await ctx.send("hello")
await asyncio.sleep(3)
await message.edit(content="hello but 3 seconds later")
is this against tos? i want to make a bot that notifies everyone in a private friend server when someone is playing a game in roblox and when they log off.
It's not against discord tos
afaik its not againsts tos if its not automated/mass dming/advertising and follows ratelimits
is this new? https://discord.com/developers/docs/tutorials/hosting-on-heroku 👁️👁️
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
it won’t be mass dms, just eventual
yeah youll be fine just follow ratelimits so your bot doesnt get ratelimited
i’ll have a rate limit of 5 sec
remember ratelimits are dynamic per endpoint
how do you do rate limits in python? i only know njs
i think 5 seconds should be fine
you can use asyncio.sleep when iterating through the members
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
i could probably just use this in a while True loop right
how can i make my prefix @bot ?
yeah but you would still need to iterate through the members so it would just iterate through the members forever
ok
!d discord.ext.commands.when_mentioned
discord.ext.commands.when_mentioned(bot, msg, /)```
A callable that implements a command prefix equivalent to being mentioned.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
> Changed in version 2.0: `bot` and `msg` parameters are now positional-only.
>
>
i don’t understand how to implement it correctly
wouldn't it be better to use a tasks?
well if they want to check something every certain time frame yeah
how do i implement it
you can iterate through all the members in a guild and try to send a message to them but have a try and except ofc
!d discord.Guild.members
property members```
A list of members that belong to this guild.
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!d discord.Forbidden
exception discord.Forbidden(response, message)```
Exception that’s raised for when status code 403 occurs.
Subclass of [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException "discord.HTTPException")
haha😅
discussing plans for a mc world
ah nice
that would be if i was dm’ing people tho right
yep
isn't the tag of task !d discord.ext.tasks?
what if i just want to send a message in a channel
yeah, it doesnt work with the bot since its undocumented iirc so if you want the deco you would need to add .loop
😦
you can get the channel from cache or fetch it from the api
how
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
yeah i know how to fetch the channel but how to i rate limit with it
pardon?
i still dont understand😅
you said i should rate limit my messages so it isn’t against tos or something
ahh, you can always just get/fetch the channel once if thats what youre asking about
.
how do i follow rate limits im so confused
for which endpoint?
what’s an api endpoint i’m confused
if your asking what wrapper im using im using ro.py
e.g to send a message in discord your client must make a POST HTTP request to discords REST API
its a url that redirects you to a server that has resources ig
what
never heard of such wrapper in my life😭
ain’t a known one
roblox api
🤷♂️
well roblox does have an api yeah
is there a difference between class SlashClient and class SlashBot?
Hi, can I ask someone some questions about hosting bots?
#965291480992321536 is the more appropriate channel
okay, thanks
👍
just the namespace if youre subclassing the Bot class it should be named SlashBot
wdym? sorry- am dumb
those are 2 different class names i suppose?
im way beyond confused- please enlighten me
also- I cant get slash commands to work lol ><
well youre asking the difference about 2 different class names, or?
btw nice nana pfp, shes underrated
I was looking at the gist for slash commands and didnt understand the difference between the two examples
ah ash's gists, well one is subclassing discord.Client while the other is subclassing discord.ext.commands.Bot so the difference would be methods and attributes
ah- I'll pretend like I understand

anyone experienced using aiosqlite in their discord.py projects?
Whats wrong with it?
it isn't adding any slash commands- or even responding when I send them
and what are u using, discord.py, disnake?
gimme an example slash command you wrote
i was just in #help-avocado if you want to look at the code?
mhm- it is updated ^^
yh i got nothing gl
💀
I had a similar problem but with disnake but i fixed it by updating it and setting intents
anyone know why this doesn't work to add a role
role = discord.utils.get(client.get_guild(ctx.guild.id).roles, id=vrid)
user = discord.utils.get(client.get_guild(ctx.guild.id).members, id=ctx.message.author.id)
Also wrong bot was in the server 💀
You can just use ctx.guild.get_role()
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
haha thanks
yw!
It seems like I will have to learn something about git and github to host that bot
@commands.command()
@cooldown(1, 1, BucketType.user)
async def flip(self , ctx , amount : str , side : str = "head"):
user = ctx.author
x = random.randint(1, 2)
try:
amount = int(amount)
bal = await economy.find_one({"id": user.id})
if bal is None:
await self.open_account(user.id)
bal = await economy.find_one({"id": user.id})
if amount > bal['cash']:
await ctx.send('You do not have enough money to coinflip that much')
elif amount <= 0 or amount > 50000:
await ctx.send('You cannot flip 0 , less or more then 500000')
else:
if x == 1:
msg = await ctx.send(f"**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}** \nThe coin spins... :coinflip:")
await asyncio.sleep(4)
await economy.update_one({"id": ctx.author.id} , {"$inc": {"cash": + (2*amount) }})
await msg.edit(content=f'**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}**\nThe coin spins... :paodcoin2222: and you Won :oiionk: {amount*2} ')
else:
msg = await ctx.send(f"**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}**\nThe coin spins... :coinflip:")
await asyncio.sleep(4)
await economy.update_one({"id": ctx.author.id} , {"$inc": {"cash": -amount }} )
await msg.edit(content=f'**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}**\nThe coin spins... :paodcoin2222: and you lost it all... :c ')
```
except ValueError:
if amount == "all":
bal = await economy.find_one({"id": user.id})
amount = bal["cash"]
if amount > 50000:
amount=50000
if x == 1:
msg = await ctx.send(f"**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}** \nThe coin spins... :coinflip:")
await asyncio.sleep(4)
await economy.update_one({"id": ctx.author.id} , {"$inc": {"cash": + (2*amount) }})
await msg.edit(content=f'**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}**\nThe coin spins... :paodcoin2222: and you Won :oiionk: {amount*2} ')
else:
msg = await ctx.send(f"**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}**\nThe coin spins... :coinflip:")
await asyncio.sleep(4)
await economy.update_one({"id": ctx.author.id} , {"$inc": {"cash": -amount }} )
await msg.edit(content=f'**{ctx.author.name}** spent :paodcoin2222: {amount} and chose **{side}**\nThe coin spins... :paodcoin2222: and you lost it all... :c ')
else:
await ctx.send(':negative_squared_cross_mark: | use correctly!!! \n \n `!flip <amount / all>`')```
any batter suggtion for this command ?
Definitely look into reducing nesting, especially by not putting everything inside of a try/catch block
What should it do?
Also, consider extracting certain logic into their own functions
hmm btw just asking will it affect bot performance ?
just asking
No, it won't
No but it will make ur code readable
ohh got it ,
will try to make it with batter logis
logics
Good idea
Whats the command supposed to do tho?
its just flip tha coin if u win your mony will 2* else lost everything
money*
how do you do rate limiting with messages
Like spam detection?
Sorry? I'm not understanding. Do you mean like a cooldown on commands?
We will never know
yeah
not exactly, i’m making a ‘party’ bot for a private server between a few friends where it’ll tell everyone when someone is in a game and when they leave. i don’t want the bot to go over rate limits and etc.
U can just store messages in ram and wipe every x seconds and if there are n amount of messages stored from a specific user then they are spamming
aight
!custom-cooldown | this should also work
Cooldowns in discord.py
Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.
from discord.ext import commands
message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)
@bot.event
async def on_message(message):
bucket = message_cooldown.get_bucket(message)
retry_after = bucket.update_rate_limit()
if retry_after:
await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
else:
await message.channel.send("Not ratelimited!")
from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.
Ah. Message rate limit is about 5 messages/5 seconds, so just stay within that and you should be OK
is there any way to detect a change in an api?
I dont like this cus u cant make exceptions with it
Unless the API tells you, no. You can also poll
i was planning to use a while True: and just compare variables
is that what polling is?
why not
Hey does anyone knows if discord-ext-menus works with discord buttons instead of reactions?
Idk It’ s the way it works, I believe it says in the docs
But ik I tried it and I couldnt make it not warn admins
you can just check manually inside the on_message
It was long time ago so I don’t remember what exactly I had going on but i think I did that and it didn’t work
can i make a countdown on an embed
use timestamps
You can edit embed every second
that works
can i edit a specific part of an embed or does it need to be the entire one
Ig u have to edit the message and replace the embed each time
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
while True:
# do stuff
client.run(token)
would this work still? like would client still run
or do i need my while loop under
i need to do it for what i’m doing
client.run isn’t in that loop
nvm that, how can i make this work?
Tb = {1837, 2847}
for i in Tb:
while True:
#d
make a while loop for each key in the table
it wont iterate through the other element tho
that’s what i’m trying to do
iterate through each item and make a while loop for each
!xy
xy-problem
The XY problem can be summarised as asking about your attempted solution, rather than your actual problem.
Often programmers will get distracted with a potential solution they've come up with, and will try asking for help getting it to work. However, it's possible this solution either wouldn't work as they expect, or there's a much better solution instead.
For more information and examples, see http://xyproblem.info/
how do i ask this uhh
how can i make a iterate through each item in a table and make a while loop for each
my problem is that it only takes the first item in the table instead of both
what affect the bot working most ?
is it long code ?
or bad code ?
or something else
Is there a way to pipe the audio from my python script that plays audio files into my mic in a discord voice channel?
How can I change second in min sec format ?
Like if i put cooldown , it retry after gives in seconds
I want to display it in min sec format
!datetime
!timedelta
Nope
#bot-commands
I know how to limit a slash command's use to a certain role... but is there any way to make it not appear in the menu for people who aren't that role?
self.load_extension('app/__init__.py')
Would this successfully load my __init__.py file in my app directory?
No, folders need to be seperated by a . and there's no .py extension
Also given your __init__.py has a setup function, yes
But an __init__.py file should not be used for this purpose
I’m using it for handling webhooks?
Great article, thanks
Still trying to figure out if I can hide it by default through the bot for all servers or an admin must configure it
@app_commands.checks.has_permissions(administrator=True)
I have this above my command
can i define a specific prefix for an entire cog?
why did i get this error ?
show code.
ok
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
@bot.command()
async def start(ctx, message):
user_message = str(message.content)
words = ["money", "hello", "bot"]
rng = random.choice(words)
print(rng)
await ctx.send("The game has started! I have generated a random word. You must try to guess it. Good luck!!!")
if user_message == rng:
await ctx.send("Congrats you have guessed the word. The word was " + rng)
bot.run(token)
@raven bolt
wjhat?
The game has started! I have generated a random word. You must try to guess it. Good luck!!!
and then the user guesses the word after the bot has said that?
i am just confused ab the error
yes
it generate a word after !start
yeah not how that works, you'll have to use the on message condition and set a flag that a game is currently ongoing
wat
per server per channel using a dict object or anything else.
i am confused
anyway probably because you just did !start
ctx already gives y ou the context
how
use ctx.message.content
wow the discord bot channel; is a lot faster to gettinh help
it doesnt work
@raven bolt
what isn't working?
you didn't include message
ok so i used ctx.message.content and i used it to chek if the user message is = to the random work
message is an argument to your command
i told the correct word but it didnt say the winning message
the only way you can use it is !start (message)
no
yes.
i fixxed that
according to your code yes.
what's your code now?
ctx.message.content returns the entire message, not just a word
that's not how it works.
oh god
as i told you earlier
what did i do now
you'll have to set a flag that a game is ongoing, preferably in a dict object htat keeps track of ongoing games for each channel.
and then check in on message
i have no idea how to do that
Seems like you probably want an on message listener
^^
but i only want it to check if u say !start
then you should be able to check
.
i am sorry
then you'll need some type of flag like redd said
wdym flag
like a bool
start = False
if message.content.startswith(!start)
start = True
if start == True:
#the start message
so like that
@raven bolt
@slate swan
This is a command, you have to invoke it like:
!start <message>
but I'm guessing this is not what you want. You can get the message using ctx.message.content
!d discord.Client.wait_for If you want to get more input after the command, use this
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.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@bot.event
async def on_ready():
numofservers = len(bot.guilds)
print("We have successfully logged in as {0.user}".format(bot))
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{numofservers} servers!"))
@tasks.loop(seconds=5)
async def status():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers!"))``` the task doesn't work
!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...
sowwy
I just do
@bot.listen('on_message')
yeah but bot would be an instance of discord.ext.commands.Bot
I don't actually name it bot, just example
what👁️ 👁️
I never name it bot or client, anymore...
like people do bot = commands.Bot
Name your bot instance the_actual_instance_of_the_commands_dot_bot_class
Which method should I use to include the number entered by the user in the variable?
wdym method?
when making open-source bots, never mention the bot's actual name in the source code
I want to put the number that the user entered into the int-type variable called page
make sure it's fork-able
can you show an example command usage of it
When the user enters the message !page 3, he or she wants to put the number 3 in the variable python pages.
hey how do i get my bot to recognize if someone has pinged a specific person?
like @loud shard
you could do
@bot.command()
async def cmd_name(ctx: commands.Context, numberentered: int) -> None:
await ctx.send(numberentered)
# sends the number you entered
just an example
thanks 🙂
discord.Content isnt a thing👁️ 👁️
I forgot what it's called
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
oh so it's commands.Context
my fault 💀
@drowsy prairie keep in my mind I just annotated the variable you probably have to add int type when you try to use it
😭 ✌️
just call the int function on the variable when you try to use it @drowsy prairie
right? @slate swan
yes I was looking for it
yes that's right
converters are merely type hints
wdym
in a func
typehinting automatically converts it?
dpys converter converts the type annotated and passes the arguments with that type when internally called
Oh
no no dpys converter, typehints in python are a theory
You don't have to call int on the variable when you use it then @drowsy prairie
!e
def a(b: str):
...
a(1)
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
However, the number in the variable must be changed every time the user enters it
Why don't you test it out 😉
i will 🙂
if you need help after trying, then you can ask here
thank you 🙂
i barely know how to cook rice😔
you can do it in python though
all fun and games until i sleep on the task too much and burn the rice🗿
?!
can anyone help me with "'BotBase.load_extension' was never awaited error after i switched to discord.py 2.0
can someone tell my how to fix this error? It came when i used a command
Just add await in front of your load_extension
Can we see the command?
thats all i have to do?
ive been told i need to do more but they still didnt work
What did you try?
And how do they "not work"
some said i had to do something like
async def main():
async with client:
await load_extensions()
await client.start('your_token')```
that didnt wotk
work*
how do i do setup_hook?
async def MyBot(commands.Bot):
...
async def setup_hook(self) -> None:
await load_extension(...)
bot = MyBot(...)
bot.run()
You can also do other stuff like setting up a database connection, setting up an aiohttp.ClientSession, and syncing your slash commands here if need be
def findKeyword(keyword):
for i in range(1, pages):
@client.command()
async def searchsetup(ctx, page):
f = open("setup.txt", "w", encoding="utf-8")
await ctx.send("page : " + page)
f.write(page)
#pages = open("setup.txt", "r", encoding="utf-8")
#pages = page.readline()
print(type(page))
print(page)
page = int(page)
print(type(page))
print(page)
pages = page
print(type(pages))
print(page)```
The pages of the findKeyword are not changed.
May I know why?
why subclass the Bot class when you can just overwrite the method with a callable?
idek nothings working
Personally think it looks neater, and allows for a lot more customization ¯_(ツ)_/¯
If you copy pasted what I sent, then no, obviously not. What I sent is meant to be a skeletal blueprint, not a fully working, plug and play code
🤔
I want to make a command ,
Eg , !add [bank | cash ] amount , i know amount will be int , how can I do the middle one ????
Only work with bank and cash word and if not provided it choose bank !!!!
sorry for extreme late answer; but heres the code, i created this in 4 minutes thats why its bad rn
@client.tree.command(name = "roles", description = "Role Test Menu.", guild =TEST_GUILD)
async def roles(interaction: discord.Interaction):
await interaction.response.send_message(view=RoleButton(), ephemeral = True)
##################################################################################################
class RoleButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label='Role Menu', style=discord.ButtonStyle.green, custom_id='Role Menu')
async def rolebutton(self, interaction: discord.Interaction, button: discord.ui.Button):
pass
test1 = discord.utils.get(interaction.guild.roles, name='Test1')
test2 = discord.utils.get(interaction.guild.roles, name='Test2')
if test1 in interaction.user.roles:
df = True
elif test2 in interaction.user.roles:
df = True
else:
df = False
options = [
discord.SelectOption(label="Test 1", value="Test 1", default = df),
discord.SelectOption(label="Test 2", value="Test 2", default = df)
]
@discord.ui.select(placeholder="Select",custom_id="test",max_values=2, options=options)
async def _action_select(self, interaction: discord.Interaction, select: discord.ui.Select):
await interaction.response.send_message("Done!", ephemeral = True)
##################################################################################################
So, this obviously doesn't work, and I know that. But this is an example of what I am trying to do; essentially, I want the slash command to send the "Role Menu" button. Then when it it clicked by a user, check if the user has "test1" and "test2" roles. If they do/don't, then set the default selectionOption to T/F, then send the select. How can I change this to have it work how I want it to?
await ctx.guild.create_category(name="Test")
await ctx.guild.create_text_channel(name="Test", category="Test")```
I want it to make the category "Test" and then grab its channel id and set it as a variable to make a channel under the category "Test", and every time the command is run the variable is cleared and set to a new value
if youre going to customize the class yeah its better, but just to overwrite a method seems redundant
Diff between,
Await asyncio.sleep(5) and
asyncio.sleep(5)
,Like what await will do here ?
!d discord.Guild.create_category
await create_category(name, *, overwrites=..., reason=None, position=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.
Note
The `category` parameter is not supported in this function since categories cannot have categories.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
that doesnt help
Hello! How can i make my bot also DM the user it picked?
category = await guild.create_category
await guild.create_text_channel(category=category)
hmmmmmmmmmmmmmm
It was so I can read the docs
it would schedule the coroutine in the event loop and return the return type of the coroutine over returning a coroutine object
create_category method returns channel that was just created of type CategoryChannel
little bit in simple language ? 😳
okay....
member = random.choice(guild.members)
await member.send(message)
how do I choose the category name?
the coroutine doesnt get scheduled and it returns a coroutine object so it never gives ownership to the event loop and wont sleep on the task so other coroutines could run
When u create category
I'll try
lemme test smth
Ohhhh 😦 dangerous nvm
alright I got it
I suggest u look online for some articles about asynchronous programming
So u get an idea of what It’ s about
Can u gimme link ? Small help
😳
This series of videos introduces AsyncIO to Python programmers who haven't used it yet. The first episode is a high-level view on the async ecosystem. We cover:
- why you'd want to use asynchronous code at all;
- how latency drives the user experience;
- what the difference between concurrency and parallelism is;
- some of the problems you can...
Thanks buddy 🫂
Best tutorial on how to learn asynchronous programming paradigm is experience imo
I want to make it so u can add spaces in the prices name but then it doesnt know how long the giveaway should exist and i dont want to switch the order of the arguments
Help me
Screenshot of the code? Maybe i can help
How do I make the name of the cogs in the title and the command names in the field values like this?
if you want to add spaces, you can do something like this !giveaway "price with spaces" time
ok but how would random users know they have to put " infront and after?
well, think about this, how would the discord.py know what you add spaces, its part of prices or not
another thing you can do it add another parameter and check if its None, then assign it to time or something
like
def foo(a, b=None, c=None):
if b is None:
c = b
...
foo(1, 2, 3)
foo(1, 3)
why do you want price to have spaces btw?
and what type are you expecting
maybe you can type hint with it Greedy object
if someone wants to say "Discord Nitro" it needs a space or if they have some other item with spaces they want to give away
Consume all with multiple args just don't work with how discord.py is designed
You'll need command flags but that's kind of a pain to setup IIRC unless it's better supported now
You can always just do something like py async def giveaway(ctx: commands.Context, price, *, time): ... then run via `<prefix>giveaway "$100" 10h
an easier solution would be to use slash commands, they provide input boxes where user can enter things with spaces depending on type
Also price? Did you mean prize??
.
Note the quotation marks are important for the spaces
So <prefix>giveaway "foo bar" 10h
Can someone help
!d discord.ext.commands.Bot.cogs
property cogs```
A read-only mapping of cog name to cog.
!d discord.ext.commands.Cog.walk_commands
for ... in walk_commands()```
An iterator that recursively walks through this cog’s commands and subcommands.
!d discord.ext.commands.Cog.get_commands
get_commands()```
Returns the commands that are defined inside this cog.
This does *not* include [`discord.app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command") or [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") instances.
@outer violet walk_commands will also contain groups, get_commands will not
Can I get example of what it would look like? I’m still confused
So you want to get all cogs and all commands of each command. So what you'll need to do is list of all cogs, each Cog has walk_commands or get_commands method, so you iterate through bot.cogs and for each cog through cog.walk_commands, so the example would be:
info = {}
for cog in bot.cogs:
cmds = cog.walk_commands()
info[str(cog)] = ", ".join([cmd.name for cmd in cmds])
emb = discord.Embed(title="help command", description="see commands")
for cog, cmds in info.items():
emb.add_field(name=cog, value=cmds)
Ohh
I made it to an slash command; but now all commands are getting sent twice
Two instances of bot are running
How can i fix it?
You can just reset token and restart the bot, second instance will automatically stop responding
Better solution would be to actually find that instance
To prevent it from occurring next time
Sorry for this stupid question but do you maybe know how i can find it? I only converted a command into a slash command...
second bot instance inside a command 💀
or on_message listener with process_commands
Instance is a process
It's not in your code
oh
member = ctx.author
guild = ctx.guild
role = guild.get_role(vrid)
await member.add_roles(role)
anyone know why this doesn't add the role
Any error?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
vrid is probably not correct
Failed to get role
how can i check who reacted to the message and then pick a random user of these in a Slash command?
fetch the message again via channel.fetch_message and then get reactions via message.reactions[0].users.flatten(), and then pop urself from users. Here's an example:
did i do something wrong?
but what do you mean with my_msg.id what if i dont have the message id?
but you have?
vote_msg.id
new_msg = await interaction.channel.fetch_message(vote_msg.id)
where is the problem
vrid is correct
it's an async generator object in 2.0
Sorry but i tried everything i could think of but i couldnt get it to work, I don't know what i did wrong, i fetched the message again and it gave me the same error or i get this error:
users = await vote.reactions[0].users().flatten()
AttributeError: 'PartialInteractionMessage' object has no attribute 'reactions'
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: AttributeError: 'PartialInteractionMessage' object has no attribute 'reactions'
lst = [user async for user in message.reactions[0].users()]
for list of all member objects
also make sure u are fetching the message object correctly
beep boop baap
?
i thought on_command_error would work for app commands(
on_command takes command.Context as far as i am aware and slash takes discord.Interaction so well it won't work🗿
well Context can be interaction based
hybrid commands only no for that👀
but on_command_error takes commads.CommandError and app commands - app_commands.AppCommandError
hmm idk much about slash commands never took my time with it 
understanbadle
in disnake you have both on_command_error and on_slash_command_error
gud, but im not using disnake
And that's where you're wrong
Is it possible to ban a user on leave from the guild they left
Not from the other guilds they are in
(By the bot)
ban a user thats not in the guild?
No
sorry i didnt really understand then
me2
Ban a user who leaves guild A but not ban them in guild b, c
bruh how can you even ban them in 3 guilds
....
so you'd need to avoid that
in a in_member_remove event
on_member_leave?
remove 😭
so if a user leaves guild a u wanna ban them from guild a?
oh 😳
well in on_member_remove check member.guild.id to make sure it is the correct guild then use await member.ban()
Something like
if member.guild.id == “. . .”:?
man, it’s not like I’m making it for a server
it should be an int
Is it not possible without guild id ?
well u have to check it in someway
otherwise every person who leaves a server will get banned
my bot doesnt see the 0, it thinks its 3 Minutes instead of 30 Minutes how could i fix it in the easiest way possible?
time[0] takes only 1 digit, so use time[:-1] instead, and also mo format won't work, because you take only one letter at the end and mo is 2 symbols, also who ever will create giveaways that last months of time, just remove it, cus even your bot probably won't run that long
bruh, logging is revealing my password
gimme your pass
here you go: dQyHk%6(Bd$GyH&z
🗿
also, why would you need it?
it's just a joke
lol
inline games
inline True means those fields are gonna be side to side false means it's not gonna be side to side
inline=False field will always be one in a row
yes
ban with I'd like Carl does
but when I inline=True for PUBG part. it goes to 3rd column
then it's impossible, except if you use empty fields (but that'll make your embed wider)
yes
you cannot, 2 fields in one line is only applicable at the beginning and the end
.pr
not funny + didn't laugh
!rule 7 this is not a memes channel
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
dont log debug then 🗿
setup logging level to info maybe
why not
i mean yeah unless youre testing something, it can be spammy
Hi, anyone knows why this give me undefined error in the @tasks.loop on the function calls inside the value field?
def function1():
with open("example1.txt", "r") as f:
data2 = f.readlines()
list1 = data2.split("\n")
return len(list1)
def function2():
with open("example2.txt", "r") as p:
data1 = p.readlines()
list2 = data1.split("\n")
return len(list2)
@tasks.loop(seconds=10)
async def stockedit(self):
embed = nextcord.Embed(color=nextcord.Color.purple())
embed.add_field(name="Function1", value=f"{function1()}", inline=False)
embed.add_field(name="Function2", value=f"{function2()}", inline=False)
embed.set_author(name='Infinimonster#1312')
channel = self.bot.get_channel(1002326566707150932)
msg = await channel.fetch_message(1002326851257110599)
await msg.edit(embed=embed)
print("Edited")
Print list1 and list2
See what it prints out
!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.
There is no Traceback, if there would be one i would've sent it already. it just underline the function execute line and when hovering over it it says undefined but when starting it no error appears and then commands just won't work.
guys don't give wrong answers ;-;
is that task loop in a class?
yes, it is
yeah and the functions to right?
yea
so use self.function1()
also the function is wrong
readlines returns a list of strings
and list dosent have a split method
u can just return len(data1)
No one even gave an answer
^^
-_-
that's not really as much an answer as just trying to get more information
thank you.
^
so i should ise f.read() instead?
it's not a problem but try to read the whole question and answer as op already explained which error he got
this ^^
justu se readlines and return len data1
but don't try to call .split on it because it's a list.
also since u are not using self in function1 and 2 u can decorate it with @staticmethod
Also if functions are in a class they need self argument or make em static
so is this correct?
def function1():
with open("example1.txt", "r") as f:
list1 = f.readlines()
return len(list1)
yes indeed
@staticmethod
def function1():
with open("example1.txt") as f:
list1 = f.readlines()
return len(list1)
Hey guys, I'm trying to make my bot join if the user is in a voice channel and if not, send a message saying that the user is not in a voice channel. When I run the join command, the bot joins if the user is in a voice channel, however, the message is not sent if the user is not in a vc. What is the problem here? Can someone clear up my confusion please?
@commands.command()
async def join(self, ctx):
user = ctx.message.author
channel = user.voice.channel
state = ctx.author.voice
print(state)
if state is not None:
vc = await channel.connect()
else:
await ctx.send(f"{ctx.author.mention} You are not connected to a voice channel. Please join a voice channel before using $join.")
any errors?
what does print(state) print when member is not in voice?
what did you put in the exception block?
await ctx.send(f"{ctx.author.mention} You are not connected to a voice channel. Please join a voice channel before using $join.")
Nothing
i mean the exception you tried to catch
how do i make my discord bot stay on stage
error code every 12hrs: ```
disconnecting from voice normally close code 1000
but my bot is still online
none
do you have an error handler event?
@stable mulch
if not ctx.author.voice:
What is that?
that's just the same
well my google cloud sucs if theres no other way
Thats what i did to my bot and it works fine
@event \ async def on_command_error or @event \ async def on_error somewhere in your code
Yeah I have async def on_command_error
only for commands.CommandOnCooldown and commands.MissingRequiredArgument though
put this at the end of your if-else statement:
else:
print(f"ignoring exception in command {ctx.command.name}\n{type(error)}", file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
await ctx.send(f"Something went wrong in executing command {ctx.command.name}\n{type(error)}")
you will need to import sys and traceback
alright, thanks