#discord-bots
1 messages · Page 947 of 1
ok
Also, don't use f-strings inside of queries
thanks, it works
The balance command says "database is locked" when trying to check values
it can't add them if they aren't there for some reason
Yes, but it makes no sense to use run.
If your using an async driver for your database as I've said earlier
You will need an async call to connect
You'd use run for a sync driver
okay so I saw that connect and start are coros so either would work
But I will specifically recommend start
connect is where discord.py does some important stuff
And that's where the exponential backoff is
It would be a lot safer to do it in start
Nice background \👀
Pyrite by LeafyLuigi
My thing is saying that my database is locked, any help? using aiosqlite module
Not much
login calls setup_hook and login is inside of start
It's basically the same thing except you don't override the two calls in start discord.py does
Which is calling upon login then connect
I would just make a bound method to your class that syncs
Then call it whenever you need to update a command
You can however do it automatically, but of course that means using extra bandwith every time you start your bot
And also means you use a request for X command at the start
It can probably put some stress on the API, if a lot of people do it
Perhaps that's why discord.py doesn't recommend it
If by automatic you mean calling sync when the bot starts
Yep, then what I says apply
You could make a "smart" sync
Anyone?
this is my current code, i just dont know how to make it so its only scanning a certan channel
@bot.event
async def on_message in <945861044163731476> (message):
await message.delete()
Can't be assed
if message.channel.id == ...:
How do you if its possible
@bot.command()
@commands.check_any(commands.has_permissions(administrator=True), commands.has_permissions(ban_members=True))
async def ban(ctx: commands.Context, user: discord.User):
await ctx.guild.ban(user)
await ctx.channel.send(f"{user.mention} has been banned.")
@ban.error
async def on_ban_error(ctx, error):
if isinstance(error, commands.BotMissingPermissions):
await ctx.channel.send("I cannot ban the owner.")
if isinstance(error, commands.CheckAnyFailure):
await ctx.channel.send("You Don't Have Perms Dumbass")
why isnt this error handler working
i get no error message in the channel
@bot.command()
async def testing123(ctx, userid):
with open("/root/Textfiles/changelog_ids.txt", "a") as f:
f.write(f"{userid}\n")
f.close()
This is my code, why doesnt it write in the file?
cause youre using the wrong errors
if isinstance(error, commands.MissingPermissions):
it should be this
i see
another error too
it should be like this
@commands.has_permissions(ban_members=True)
not:
commands.has_permissions(ban_members=True))
Syntax Error
you need to close an opening bracket
first of all dont close the file, it will close automatically
i got it working anyway, the bot wasnt in the server i was testing it on 😂
Getting some strange error when trying to do a warn command. Says corountine is not subscriptable. I don't know what this means and looking for some help?
Let’s see the code
You are trying to subscript a coroutine somewhere
eg: await foo()[index] probably
you oughta declare it to a variable and subscript that
yeah i forgot an await, got it working but now it's saying that the database is locked.
Doesn't do it with other db-related commands tho
@client.event
async def on_member_join(member):
channel = client.get_channel(957288621424119828)
embed = nextcord.Embed(colour= nextcord.Colour.blue(),title=f"{member}",timestamp=datetime.datetime.utcnow())
embed.add_field(name="Thank you for joining",value="\nMake sure to check \n•[#957061610139189288](/guild/267624335836053506/channel/957061610139189288/) \n•[#957061610139189288](/guild/267624335836053506/channel/957061610139189288/) \n•[#957061610139189288](/guild/267624335836053506/channel/957061610139189288/)",inline=False)
embed.set_thumbnail(url=member.avatar.url)
embed.set_footer(text="Enjoy your stay :3")
await channel.send(f"**Welcome into the server ~ {member.mention}!**")
await channel.send(embed=embed)```
its not sending the reply.. its in nextcord.py
You need to have "SERVER MEMBERS INTENT" enabled on discord.com/developers
that was dumb lmao
shi happens, sometimes i do { } instead of ( ) lol
no objections from my side
it is enabled
you also gotta do intents=intents on your client = commands.Bot()
i think.
i never got it working either, but thats what u have to do
well, the intents you pass should have .members enabled
!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 the Members and Presences intents, which are needed for events such as on_member 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.
Read that.
That should work
!d nextcord.Member.display_avatar
property display_avatar: nextcord.asset.Asset```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
like this?
Yes
hm working
!d nextcord.Member.display_avatar
property display_avatar: nextcord.asset.Asset```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
thanks
Too late 🤷
who knows
You maybe
re-think
yeah
alright so lets say
hm?
CREATE TABLE IF NOT EXISTS exp (
UserID integer PRIMARY KEY,
FISH integer DEFAULT 0,
Level integer DEFAULT 0,
XPLock text DEFAULT 100
);
this is my sql file
hm
it is always ideal to set the IDs to be NOT NULL too
UserID INTEGER PRIMARY KEY NOT NULL,
basically just UserID for the user, how many fish they have(a mini game like who has the most fishes) Level blabla
hm?
now this is the py file:
from os.path import isfile
from sqlite3 import connect
DB_PATH = "./db/database.db"
BUILD_PATH = "./db/build.sql"
cxn = connect(DB_PATH, check_same_thread=False)
cur = cxn.cursor()
def with_commit(func):
def Inner(*args, **kwargs):
func(*args, **kwargs)
with_commit(func)
return Inner
@with_commit
def build():
if isfile(BUILD_PATH):
scriptexec(BUILD_PATH)
def commit():
cxn.commit()
def close():
cxn.close()
def field(command, *values):
cur.execute(command, tuple(values))
if(fetch := cur.fetchone()) is not None:
return fetch[0]
def record(command, *values):
cur.execute(command, tuple(values))
return cur.fetchone()
def records(command, *values):
cur.execute(command, tuple(values))
return cur.fetchall()
def column(command, *values):
cur.execute(command, tuple(values))
return [item[0] for item in cur.fetchall()]
def execute(command, *values):
cur.execute(command, tuple(values))
def multiexed(command, valueset):
cur.executemany(command, valueset)
def scriptexec(path):
with open(path, "r", encoding="utf-8") as script:
cur.executescript(script.read())
So basically how do i implement that a specific user id gets their "FISH" added 1
i probably have to do it in the python file right
update the user data
to add a fish to them
Update how
Damn aight
execute('UPDATE table_name SET FISH = ? WHERE UserID = ?', fish_amount, user_id)
this will work
if you use aiosqlite
add an await since you'd be making an asynchronous function
yeah and?
Basically DB.execute()
no...
Y doe
you made the execute func here
Yes
I used execute function in context to that
Ah so i update the execute file to that
um...what
quick learner
you regenerate it from the bot tab in your application page
guys I'm leaving discord
streamer = member.activities[0].url.split("/")[-1]
List = [streamer]
CurrentFeatured = random.choice(List)
await ctx.send(CurrentFeatured)
empty = False
i am getting the members who are streaming but if there are more i want to get a random streamer i tried using a list and getting a random choice but its not working i am doing something wrong can someone help me out ?
Okay
the commands are restricted with the is_owner check, so you have to either add the users to your dev team on discord or override the is_owner method on Bot
https://jishaku.readthedocs.io/en/latest/cog.html#changing-who-can-use-jishaku
Back
try:
reply = await self.bot.wait_for("message", check=check, timeout=20)
except asyncio.TimeoutError:
await choice.edit(content="Train left the station.")
return
Command raised an exception: NameError: name 'asyncio' is not defined
that means you have to import the asyncio module
import asyncio?
yes
man I couldn't fool a single soul
lmao
if a user sends a command how to wait for an user confirmation with emojis?
wait_for
Show
@discord.ext.commands.has_role(959430769086959646)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split ('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminantor) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.send(f'Unbanned {user.mention}')
return```
Just type hint to discord.User then
!d discord.Guild.unban
await unban(user, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Unbans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
like how?
user: discord.User in function args
does random.randrange include the start and stop or exclude
!d discord.Member.edit or
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
!d discord.Member.timeout this works too
await timeout(when, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.edit "discord.Member.edit").
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
Involves modifying the decorator which does a database lookup to check for differences, then if different sync command when registering
This makes it so it doesn’t auto sync ALL commands on runtime
Only those that have been modified
hey, is anyone familiar with pycord here
How to make a command to clear messages
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
Yes
thank
import discord
from discord.ext import commands
client = commands.Bot(command_prefix= "PREFIX", activity=activity)
@client.command(pass_context = True)
async def clear(ctx, number):
mgs = [] #Empty list to put all the messages in the log
number = int(number) #Converting the amount of messages to delete to an integer
async for x in client.logs_from(ctx.message.channel, limit = number):
mgs.append(x)
await client.delete_messages(mgs)
client.run('TOKEN')
update your dpy
you don't need to pass context in the rewrite
The aztecs recognize this code more than i do
and also, put a permissions check
That dosent work.
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
made for use
?
you get the channel and use the purge method on it
with limit being the amount of messages you wanna purge
w o w @cold sonnet, how many marks u gonna give him?
i dont understand can you help me make the command?
I've never worked on a delete messages command before
but you can always refer the docs
sure, do you wanna clear messages in the channel the command's invoked in?
or SO
what's so
Stack Overflow
o
yes
im not sure how to make discord bot stuff yet
my first bot im makin
@command
@commands.has_permissions(manage_messages=True)
async def clear(ctx: commands.Context, amount: int, channel: discord.TextChannel=None):
if amount > 200:
return await ctx.send("too many messages", delete_after=20)
channel = channel or ctx.channel
await channel.purge(limit=amount)
await ctx.send(f"cleared the messages in {channel.mention}")
ew
A bit
what
you're just an ew Ashley
i have made
breh
thats rude
some commands already
how is he gonna learn from spoonfeed 😠
you gonna explain
thanks
you can refer to this @latent ember
bye
what is this sh*t talkin? D_D
stop with the drama
just use ctx.channel.purge(limit=x)
Just the usual drama 🤷♂️
im pretty sure thats right
Yes
Oop my bad xD
took me 2 weeks to learn cogs :/
1 day D_D
oof
i've learnt d.py in less than a week, then learned slash commands and other interaction in disnake in few days D_D
yes but
it was exam month 💀
now it works
Make that like 3-4, if not, 5 months for me
how would i go about the database
sqlite?
#define command
@bot.command()
#check for manage_messages permission
@commands.has_permissions(manage_messages=True)
#command name, taking ctx as always, an amount that has to be a number, otherwise error, and a channel that can be none
async def clear(ctx: commands.Context, amount: int, channel: discord.TextChannel=None):
#if the number's too low
if amount > 200:
#stop and send that's too many, message deleted after
return await ctx.send("too many messages", delete_after=20)
#channel stays the same or it will be the channel the command's invoked in
channel = channel or ctx.channel
#purge the amount of messages you wrote in the command
await channel.purge(limit=amount)
#send that it was cleared
await ctx.send(f"cleared the messages in {channel.mention}")
i mean
overcommenter yes
if you never used a db before use sqlite (builtin database in python) with aiosqlite package
@cold sonnet do you know how to make the bots message delete after saying messages cleared
when you send the message assign it to a variable
then delete
delete_after kwarg
example in the return await one above
i just did something like msg = await ctx.channel.send(embed=embed)
then msg.delete() i think
ctx.send better
force of habit ;/
from discord.ext import commands
from webserver import keep_alive
import os
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print('Bot is ready.')
@client.event
async def on_member_join(member):
channel = client.get_channel(959102280731361302)
embed=discord.Embed(title="Welcome!",description=f"{member.mention} Just Joined")
await channel.send(embed=embed)
@client.event
async def on_member_remove(member):
print(f'{member} has left an server.')
@client.command()
async def ping(ctx):
await ctx.send(f'ping is '+str(round(client.latency * 1000))+'ms')
@client.command()
@discord.ext.commands.has_role(959430769086959646)
async def kick(ctx, member : discord.Member, *, reason=None):
await member.kick(reason=reason)
await ctx.send(f'Kicked {member.mention}')
@client.command()
@discord.ext.commands.has_role(959430769086959646)
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'Banned {member.mention}')
@client.command()
@discord.ext.commands.has_role(959430769086959646)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split('#')
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
await ctx.channel.send(f"Unbanned: {user.mention}")
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx: commands.Context, amount: int, channel: discord.TextChannel=None):
if amount > 200:
return await ctx.send("too many messages", delete_after=20)
channel = channel or ctx.channel
await channel.purge(limit=amount)
await ctx.send(f"cleared the messages in {channel.mention}")```
this is my bot rn
how to make the latest command or all the commands messages delete automatically after a short time?
I think you'd have to put delete_after x in every send
can you iterate through messages in a channel?
or (just something you won't do, neither will I)
subclass context and make your commands return ctx as that subclass
in that subclass, change the send function to having a default delete_after
there has to be an easier way
like commands.Context.send.delete_after = 5
(won't work don't try, just an example)
it's not better
yes
it's literally the same as ctx.channel.send
with what
we talked about this
who
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
i see
@bot.command()
async def purge(ctx, member: discord.Member):
async for channel in ctx.guild.channels:
async for msg in channel.history(limit=100):
if msg.author == member:
msg.delete()
something like this then?
you realize that
member would be the bot in his case
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
is a thing
and you can just pass it a lambda check that checks if message.member = member
yes, you can do that using the purge coroutine
def check(m):
return m.author = member
await channel.purge(limit=100, check=check)```
should do the trick
where users have a profile in each guild
how would i do that with something like mongo
probably belongs in #databases
but does anyone know
i see
me when i forget how to use lambda
lmao
that's a little complicated
you need a document just to store which members belong to which guild
and then several pointers for each member in the guild
hmm
it's something worth opening a discussion somewhere else about
that is complicated
because it'll get a little complicated
the people in #databases will probably laugh at your face
for not using their holy sqlite database types
still, good luck
lmao-
they're mean 
ill probably end up learning sqlite
i need it to join my school's it council
need to learn django too
whats the equal to cursor.execute in aiosqlite
no?
nvm seems like ive done something wrong
being rude isn't tolerated here lmao
who cares kayle, i was just joking
lol
it's just a one liner function
i forgot to learn lambda 
def main():
print(1):
``` is the same as ```py
lambda: print(1)
i see
i know what a lambda function is
how would he check for the dm tho
Make sure the sent message is in a dm
Use the wait_for method, and get the file by doing ```py
message = wait_for(..., ...)
message.attachments
Without a check, this would pick up the first message, so a check is paramount
Well robin that is why I used ellipsis
Return true if:
- the message is from the person who used the command
- the message contains an attachment
- the message is in a DM
Traceback (most recent call last):
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\leka\PycharmProjects\Amk\fishergame_cog.py", line 15, in getfish
await db.execute("UPDATE exp SET FISH = ? WHERE UserID = ?", ran, alpha)
File "C:\Users\leka\PycharmProjects\Amk\db.py", line 48, in execute
await cur.execute(command, tuple(values))
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
AttributeError: 'Result' object has no attribute 'execute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Result' object has no attribute 'execute'
So im testing out a db with aiosqlit eand ive got this error
def check(message):
...
``` or ```py
lambda message: ...
``` `...` being the stuff you need to check for
Whats Result?
Idk atleast it isnt something i set up
hold on ill send the other ocmmands
No
?
hm have you tried 
oh yeah they have that filter thing now
i opened it and got this 3d glasses one that blinded me
most of the problems there were because of misspellings
i assume theres a difference from mysql(outside of the await and async functions) in aiosqlite with cursors?
ill ask in databases
👍
yay, finally made a reminder system for my bot
that DOESN'T use asyncio.sleep
btw can text commands have keyword args? like !mute reason="loser" member=879807617260716143
Please help me set up the command
@client.command
async def cash(ctx, member: discord.Member):
print('cash')
cash = cursor.execute("SELECT cash FROM economy WHERE id = ?".format(member.id)).fetchone()[0]
member = discord.Member
await ctx.send("Показатель HP" + member + "составляет" + cash)
You know @unkempt canyon's !eval command, any easy way to create one like it?
!eval
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
Sure. Piston has an API
Piston?
Yeah, alternative to nsjail
Do you have a link?
Thanks!
or, if you want something else, try nsjail by google (i think)
@sick birchCan you please help?
with what?
Is this right? https://emkc.org/api/v2/piston/execute?
Personally, not sure. I haven't used piston
I only did code execution once by spinning up a docker container which is inefficient
@sick birchI can't make a command to work
@client.command
async def cash(ctx, member: discord.Member):
print('cash')
cash = cursor.execute("SELECT cash FROM economy WHERE id = ?".format(member.id)).fetchone()[0]
member = discord.Member
await ctx.send("Деньги" + member + "is" + cash)
Read their documentation and get it from there
Have you used nsjail?
"i can't make a command to work" meaning?
Nah, only docker
Can you help me make a variable please
What variable?
@sick birchcash = cursor.execute("SELECT cash FROM economy WHERE id = ?".format(member.id)).fetchone()[0]
You're aware you're supposed to be using aiosqlite?
And what is it? Module?
@sick birch Can you help me with some kinda paging-bot?
i was trying with the code on stackoverflow, but doesn't works for me
I am using discord.py to make a bot, and there are more commands than can fit on one page for my custom help command. I want the bot to add 2 reactions, back and forward, then the user that sent th...
im using discord.py 1.7.3, is it ok?
!jsk py 1+1
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
My bot uses global variables in order to work. How do I make it have different global variables for different users?
Without rewriting much code
why not bot variables
to transfer through cogs and such
and not having to use global everytime
and global variables for each user?
dicts goated
rip
@slate swan you came right on time
Ignoring exception in command fish:
Traceback (most recent call last):
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\leka\PycharmProjects\Amk\fishergame_cog.py", line 15, in getfish
await db.execute("UPDATE exp SET FISH = ? WHERE UserID = ?", ran, alpha)
File "C:\Users\leka\PycharmProjects\Amk\db.py", line 48, in execute
await cur.execute(command, tuple(values))
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
AttributeError: 'Result' object has no attribute 'execute'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 923, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 196, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Result' object has no attribute 'execute'
help
i assume Result is the cursor
which init?
the init of the Result class
ah
HelpSelect is a select menu?
rip
yeah prolly
yep
what u ripping
??
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
class db(commands.Cog):
def init(self, bot):
self.bot = bot
dyou mean that?
u got this error on this line
heyhey could anýone help me with a unban command i really ran out of ideas how i could do it
self.bot.db.execute
so self.bot.db.execute = bot?
no but that's the only time when i want to set the dropdown to row 1
there are no dropdown lines
prolly
try adding them in a different order
@client.command()
async def nowplaying(ctx: commands.Context):
if not ctx.voice_client:
return await ctx.send("Your not playing any music")
elif not getattr(ctx.author.voice, "channel", None):
return await ctx.send("Join a voice channel first")
else:
vc: wavelink.Player = ctx.voice_client
if not vc.is_playing():
return await ctx.send("Nothing is playing")
em = discord.Embed(title=f"Now playing: {vc.track.title}", description=f"Artist: {vc.track.author}")
em.add_field(name="Duration", value=f"`{str(datetime.timedelta(seconds=vc.track.lenght))}`")
em.add_field(name="Extra Info", value=f"Song URL: [Click Me]({str(vc.track.uri)})")
return await ctx.send(embed=em)
``` Is anything wrong with this? When I run this command it returns me nothing and shows no error
use the tasks extension to run something every X hours
why getattr lol
idk I just did that
If it shows no error you probably have an error handler somewhere eating it
look for on_command_error anywhere
How to make the bot filter some words?
yeah look: ```py
@client.event
async def on_command_error(ctx,error):
if isinstance(error, commands.CommandInvokeError):
error = error.original
if isinstance(error, commands.MissingPermissions):
em = discord.Embed(title=' Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
await ctx.send(embed=em)
elif isinstance(error, commands.MissingRequiredArgument):
em = discord.Embed(title=' Error', description=f"{ctx.author.mention}, You are missing arguments.", color=0xCC1313)
await ctx.send(embed=em)
There we go
Make a string with words you don't want
It's eating up all your errors
Oh
Putting words in my mouth haha
Uhm
Wave link 👁️👁️
It ignores all errors that are not what you want
How do I get that fixed?
basically your error handler does this:
if error is of type X,
do this
else if error is of type Y,
do this
else the error is something else,
ignore this
You can fix it by adding an else and re-raising the error
Uh sorry I don't know how to do that
Like I got this now
if isinstance(...):
...
elif isinstance(...):
...
elif isintance(...):
...
# so far your code looks like this, this is the part you need to add
else:
raise error
ahhh
imagine if raise error also called on_command_error lmao
Recursion ftw!
stack overflow error go brr
recursion problems are the hardest to solve and the hardest to get my head around
for that very reason i hate binary trees
Haha
Throwback to when nova made a recursive @property
huh how?
Idk but he did it
I don’t know
Oof rip
random not really python question: I have a file for my bot sub class, I was calling it bot_subclass but that's a bit lengthy, anyone have any idea for what i should name it. I want to avoid just calling it bot since my bot var is called bot and it might get some import issues (I import my bot var from my main file in some cogs, mainly for dynamic choices based off of info in my bot var)
Your bot instance and bot subclass should ideally be in the same file, called bot.py
I am drunk rn how to delete bots message lmao
msg = await ctx.send(...)
await msg,delete()
ty xd
sad delete_after noises
only if you want a timed deletion though
yea
and why's your nick like that, it looks so weird lmao
cz Ellipsis has been saving my life 👀
I'll better be off from here
!paste
under since it blocks everything that comes after it
so basically make it the last command you run in main
So how do i get the cooldowns from commands.cooldown and how do i make an error handling(if user is on cooldown and tries to use the command again)
how can I use slash commands in a cog? is something wrong?
handle the on_command_error event and check for the commands.CommandOnCooldown type, then you can use the error.cooldown and error.retry_after attributes to get more details about the cooldown
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.CommandOnCooldown
note that the particular attributes slightly differ between dpy 1.7 and 2.0
this is what i have
i'm gonna flip. i can't get discord-py-interactions working on my aws.
it just tells me it's not there
@commands.Cog.listener(name="on_command_error")
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(str(error))
even though it's literally right there in the folder with every other package
it wont let me uninstall it with pip
you need to construct your bot instance with (), not just assign the class to the bot variable
only that package has a problem
yup works @hushed galleon
<@userid> this is a mention
does the "interactions" directory in your site-packages have its name cut off with a ~ at the start? if so pip may have just messed up
you could do async def hey (ctx, whatever)
if whatever == discord.Member i think
something along that
discord.Member.id also works
idk i just manually deleted everything and am reinstalling everything to see if that fixes it
ok
if you typehint your command parameter with discord.Member/discord.User it parses both mentions and user ids for you
docs: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#discord-converters
basically if whatever == discord.Member
id = whatever.user.id
try printing the id to see if it works (should be some random number like 2142152142131)
okay i thought i deleted everything but it seems to think the requirement is already satisfied but only for that package 
how can i make asyncio create a thread?
if you dont typehint the parameter it defaults to string, which will never equal the Member type
!d asyncio.to_thread
coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.
Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.
Return a coroutine that can be awaited to get the eventual result of *func*.
This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were ran in the main thread. For example:
okay i've only got the distribution info in my package folder for some reason, searching pc for discord-py-interactions 
@commands.command()
async def mute(self, ctx, member:discord.User=None, *, reason="No reason"):
if member is None:
embed=discord.Embed(description=f"**Please mention a member you want to mute. `{prefix}mute <@member> [reason]`**", color=0x6fccd4)
await ctx.send(embed=embed)
else:
mutedrole = discord.utils.get(ctx.guild.roles, name="muted")
if mutedrole:
try:
member.add_role(mutedrole)
embed = discord.Embed(description=f"**{member.name}#{member.discriminator}** is muted sucessfully.", color=0x6fccd4)
await ctx.send(embed=embed)
try:
embed = discord.Embed(description=f"**you have been muted in {ctx.guild} for `{reason}`**",color=0x6fccd4)
await member.send(embed=embed)
except:
pass
except:
embed = discord.Embed(description=f"**Some error has occurred**", color=0xff0000)
await ctx.send(embed=embed)
else:
embed = discord.Embed(description=f"**please create a role named `muted`, and set it's perms**", color=0xff0000)
await ctx.send(embed=embed)
whats wrong here? i keep getting the error embed
okay so only the distribution info folder exists for discord_py_interactions... yet requirements are satisfied for pip
same with member.add_roles btw
@commands.command()
async def mute(self, ctx, member:discord.User=None, *, reason="No reason"):
if member is None:
embed=discord.Embed(description=f"**Please mention a member you want to mute. `{prefix}mute <@member> [reason]`**", color=0x6fccd4)
await ctx.send(embed=embed)
else:
mutedrole = discord.utils.get(ctx.guild.roles, name="muted")
if mutedrole:
try:
await self.client.add_roles(member, mutedrole)
embed = discord.Embed(description=f"**{member.name}#{member.discriminator}** is muted sucessfully.", color=0x6fccd4)
await ctx.send(embed=embed)
try:
embed = discord.Embed(description=f"**you have been muted in {ctx.guild} for `{reason}`**",color=0x6fccd4)
await member.send(embed=embed)
except:
pass
except:
embed = discord.Embed(description=f"**Some error has occurred**", color=0xff0000)
await ctx.send(embed=embed)
else:
embed = discord.Embed(description=f"**please create a role named `muted`, and set it's perms**", color=0xff0000)
await ctx.send(embed=embed)
why am i keep getting this embed? everything should be fine
Whichever you use to decorate callbacks to turn them into slash commands
Yo how can I check if a member exists in a guild
# == Variable interval ==
guild_id = 952497213945311262#guild id
status_keyword = ''#The status keyword
role_id = 959519173522890772#The role id
# =======================
@tasks.loop(seconds = 2)
async def statusCheck():
guild = client.get_guild(guild_id)
role = guild.get_role(role_id)
for member in guild.members:
if status_keyword in str(member.activity) and not role in member.roles:
try: await member.add_roles(role)
except: print(f'Try to give {member.name} role, but fail')
elif status_keyword not in str(member.activity) and role in member.roles:
try: await member.remove_roles(role)
except: print(f'Try to give {member.name} role, but fail')
@statusCheck.before_loop
async def doesnt_matter():
await client.wait_until_ready()```
The bot isn't giving the role why ( i removed the status keyword so they won't delete my message)
discord.User objects cant have roles added to them, you need to convert to a discord.Member instead and use the .add_roles() method
Client.add_roles() is extremely outdated too
@hushed galleon so sorry for pinging, can you help me with this
do you have the members and presences intent enabled in your bot constructor? and did you start the loop too?
yes
ok ty
did you try using print statements to see if the loop runs at all
oh let me try
also a more efficient implementation would be to listen for the on_member_update event and check if their activity changes there, alongside a start up task similar to what you have now to handle updating roles when turning on your bot
did not print
can you show your bot constructor with intents and also the lines where you start the loop and the bot (minus token if visible)
import disnake as discord
import os
import asyncio
from disnake.ext import commands, tasks
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='-', intents=intents)
client.remove_command("help")
# == Variable interval ==
guild_id = 952497213945311262#guild id
status_keyword = ''#The status keyword
role_id = 959519173522890772#The role id
# =======================
@tasks.loop(seconds = 2)
async def statusCheck():
guild = client.get_guild(guild_id)
role = guild.get_role(role_id)
for member in guild.members:
if status_keyword in str(member.activity) and not role in member.roles:
try:
await member.add_roles(role)
print('Hi')
except:
print(f'Try to give {member.name} role, but fail')
elif status_keyword not in str(member.activity) and role in member.roles:
try:
await member.remove_roles(role)
except:
print(f'Try to give {member.name} role, but fail')
@statusCheck.before_loop
async def doesnt_matter():
await client.wait_until_ready()
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name=f""))
statusCheck.start()
print(f"Logged in as {client.user}")```
intents.presences = True is needed for your bot to read activities, otherwise every user will just show as offline (iirc)
yes
alright
Instead of doing client.remove_command("help") consider using help_command kwarg in bot constructor set to None
also .start() should and does not need to be called in on_ready
alright
Where else could you call it from tho? I can only think of bot subclass or cog implementation
just call it before running the bot
it already has a before loop to wait until ready
Won't it cause issues with asyncio
actually maybe with dpy 2.0
well I always called the task.start() outside on_ready and never really got any issues
So before running as well
You don't need to call task.start() inside of on_ready if anything that would cause problems
Not sure how does loop mechanism work in dpy
It's a glorified while True basically
oh yeah 2.0 removes the use of get_event_loop() in the tasks extension, so it would throw a RuntimeError when called in global scope
well i say would but i currently cant test it to double check
I mean how does it start that thing
bot.run basically launches asyncio application so how can it run other async functions before
Another event loop or something
it just submits a task to the current event loop, and in 1.7 it also automatically creates an event loop when one doesnt exist
Mk
i think constructing the client also used to create an event loop too
certain characters like whitespace are disallowed from being used in text channel names
the most robust solution is keeping track of their ticket channel's id in a database
Also depends on when the task is started, because discord.py will create an event loop when ran unless given one
in 2.0 afaik thats only done in bot.run()
what's the best package for slash commands and components
It's done by _async_setup_hook
Which is called by run -> start -> login -> _async_setup_hook
that internal method uses get_running_loop, which doesnt actually create the loop
asyncio.run in client.run is what creates it
I noticed, I thought discord.py created a new one
But that's just how I did things before
yeah, there's a plethora of changes they've made
Weird how discord.py decides to care about the get_event_loop deprecation, yet still use old ass stuff
query your database when they click your button to check for their corresponding ticket
if an entry exists for them, you could also double check that their ticket channel is still there in case an admin deleted it
disnake the best option?
i know the @unkempt canyon bot finished migrating to disnake last month, like 30 minutes before discord.py's un-archival was announced
well i just found out that they dropped support to discord_slash in their server
oh actually they reverted it i think #dev-announcements
Disnake is being actively developed, therefor unstable
so done with them
To revert that is
alright but then which package is stable 
discord.py v1.7.3
If you want v2.0 things, just fork, and download through your fork's github repo
So, you basically "freeze" it
That way it isn't so unstable
your package manager should already have an option to freeze to a specific commit
pip freeze command or the poetry.lock file
That being said, discord.py and the corresponding forks (most of them at least) have no unit testing
So when things break, they break bad/hard
alright so basically just use disnake
wonder how many times dpy master had critical bugs introduced
that being said they are using unit testing for the app commands and a few other modules
yea definitely not a lot
does discord.py have dropdowns and buttons?
import cursecord
async def main() -> None:
guild = cursecord.Guild.precreate(id=...)
async with cursecordCursedClient(....) as (client, gateway, rest):
@gateway.on(cursecord.MESSAGE_CREATE)
async def message(message: cursecord.Message) -> Iterator[str]:
yield f"I got a message from {message.author}"
@guild.on(cursecord.GUILD_DELETE)
async def deleted(guild: cursecord.Guild) -> None:
print("deleted")
await gateway.setup()
asyncio.run(main())
``` some cursed idea's for my late april fools joke wrapper
oh i see the context menus
wait what does this do
what part
I mean, idk the context soooo
I’ll prob make this code work at least then delete the repo
We do a little trolling
Haha
intents
Probs cuz the name of ur function and variable are in fact the same
If that's pycharm ur using then that's most likely why
Rmr opening a repo on that and got 200 pep errors
no i have the same in pycharm
Bro
How do I strip all punctuations from a message and then match it?
@bot.command()
async def embed(self, ctx, title, *, description):
embed = discord.Embed(title=title, description=description, color=0x1630C3)
await ctx.send(embed=embed)
``` try something like this and make every change you want
intents it
It's probaby because embed is already the name of the function
@vale sierra lets not post things like that please
no no i have it
?
how long do you think until discord.py 2.0 is working well 
i have it in my code its not this
That warning is just pycharm telling you that you are reusing a name
Shouldn't affect your code running though
yes sorry indent haha
there wasn't anything wrong with indentation there
the indent is wrong here
on what line?
hmm not i say bullshit @proven shale delete self, title, description please in the code
In your case, embed is the name from the outer scope
I would suggest using a different variable name for that embed
or even just putting it directly in the send
but its dont affect the code i think bc i have the same in my code
Your function name?
Well now your command is <prefix>embed_func
If you want to do it that way, you can name the function by using
@bot.command(name="embed")
What exactly did you try here?
That's not exactly how you send commands
Did you run your command with <your-prefix-here>embed_func?
But that command is not help
it is embed_func
No, it would just output embed_func as a literal string
Do you know how the command system works?
I'd suggest going through some parts of this, maybe learning how that part of it works
https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
can i do a thing where if someone sends a command, i activate a different "function" only when the corresponding value is passed through the comand?
Well yes because copy pasting won't get you anywhere, and all the videos code are outdated and suck
i was thinking using await wait_for() but can i make those also check a channel?
Don't change presence in on_ready, and you need to process_commands if you're using an on_message event.
hey guys, if anyone is interested to host a bot 24/7 in python totally free I have a youtube video that was really helpful for me. my bot is now hosted without paying anything. of course you can pay to upgrade it but that's not important
Why would you need wait_for?
who has invite link for discord.js serv3r
You can just call a function if an argument is equal to something
logs = commands.get_channel()
general = commands.get_channel()
i have this as my code in a cog, once it gets to this part it wont send and says, no attribute get_channel
who has invite link for discord.js serv3r
thanks bro
If yo have an on_message event, then commands won't work
What is commands type?
I need help making a mute command
guys how do i subclass the Client?
cand someone teach me
class Commands(commands.Cog):
"""Moderation commands!"""
def init(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(Commands(bot))
!cod
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I'm talking about lowercase c, commands
the variable you're invoking .get_channel on I mean
ctx.guild?
fixed that lol
what do you mean?
Looks like you're calling .get_channel() on commands I just want to know what that is
wait for a specific user to send a message, with a timeout of x minutes
Wait for them after a command has been invoked?
yes
Or just invoke a command with an argument?
oh what the meaning of get.channel is
Ah, I see. Then yes, wait_for is your best bet
someone invokes /start_game and then we wait for the relevant player to send a message
No no, I want to know what the commands variable is
I see, my bad about the misunderstanding. Yes, use a wait_for paired with a check
since if a player doesnt respond within the time limit they get removed from the player list
you could honestly just remove the on_message function altogether
but how can i make it pick which wiat_for() section to use
process_commands() takes a message instance
What do you mean by "section"?
i guess im not understanding
client = commands.Bot(
command_prefix = ".",
case_insensitive = True,
intents = discord.Intents.all())```
you mean this?
logs = commands.get_channel()
general = commands.get_channel()
^^^^^^^^
yea i know but im not understanding what you mean by "what the variable is"
i get which word youre talking about, just not what youre asking
What are you assigning to it basically
ohhhhh
logs = commands.get_channel(958932470710030431)
general = commands.get_channel(919024467353677883)
await logs.send(f"{user} has been permanently global banned by {ctx.author.mention} for {reason}!")```
this?
No, it should look like
commands = # what's here?
oh, one second
contemplating whether to migrate to disnake or wait a couple weeks and hope that a stable version of discord.py comes out 
i don't have any code like that
both seem like terrible options
i have (currently) two games started with the same command
based on the int value of the argument it takes
mmm i have an idea that might make my current line of questioning irrelevane
yea i dont have commands set to anything
wait
hmmm ive kidna fucked myself here cause i dont wanna gore my code but i think i have to slice up large swaths of it
👍
disnake is nice
you mean months?
alright disnake it is
plus disnakes implementation is pretty good unlike dpy which main has allot of asyncio breaking changes
Is it possible to make the bot ignore the channel in on_message?
yeah just check the channel id
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if it’s a private message.
The channel ID.
😔 Cannot fishhook int.created_at since typehints don't work
or maybe you arent good enough
Check would be a callable that takes the same parameters as the event, then you return a bool
If the callable returns True it will capture that, otherwise ignore
how to make an mute command?
lib?
message = await client.wait_for("message", check=)
!d member.unmute
you can pass a callable in the check kwarg
no
im joking i know youre good master
Ok, so you are using the message, event. This event gives you 1 single discord.Message instance, so make a function that takes the message. lambda message: ... Now just return a bool for whatever you are checking
lambda message: message.channel.id == 1234567890
i.e it would only return the message channel only if the callable returns True
what
what you mean
Umm im not sure
yes
which version?
That sends a second message? And doesn't edit the current one
what
master?
like sending a embed then a message with interactions
pardon?
im tired idk
you mean sending a followup message?
the newest one
im tired as well bro
that you can download
Like you send one message that's an embed and then directly after that you sent another message and that's a regular text message
i feel like my brain just developed a lot of new neuron connections
thank you for making me have ot comprehend lambdas
this one?
thats master yes
what lib
so how to make the command to give people muted role?
just use the discord timeout feature?
i have the followign garbage no good code that definitely wont work, how can i make it so this loops that check for a message in teh wait_for() once a game has started up until a game has ended
really?
that wont work and wdym
and you cant use is
why ant i use is
yes what is worng with that
does is not return a bool?
idk
were on like 3.10?
nothing just tired and dont really wanna do extra work rn
thats outdated a olot
wanna just add an mute command.
its used for comparing entities
he ment the dpy version
ah
im comparing a users id to a users id
shoudlnt they be the same
its used to compare objects
the is operator checks object identity, i.e. is a the same object in memory as b, which usually isnt what you want since you need to be extra sure you're expecting the same object - even with integers, it is still possible for python to construct two different integer objects with the same value
message.author.id is an object, no?
it doesnt work like that
alright well i can use == thats not a problem
for most purposes the appropriate operator is == which checks equality, i.e. disconnected from memory location
!d is
No. It's an int. message is an instance of the discord.Message object and message.author is the instance of the discord.Member (or User) object
ok so back to the more pressing issue
i need it to always be waiting for that message
which message
the message im waiting for in wait_for(...)
what about the method
i need this to be always active, or active whenever a game is being played
not only on a one of event occuring
and on_message foesnt work becasue i cant seem to implement a timer in it
well, not effectively
!e
print(False is 0)
print(False == 0)
@glacial echo example on is
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
003 | True
first print statement returns False as theyre not the same object but the second one returns True as 0s bool is False
!e
print(bool(0))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
False
are the interactions coming from buttons? if so the View class is best suited for this
is compares objs while == compares values
not at all
someone runs a command of syntax /start_game [int] where int determines the game to eb played
then once a game ahs started all players in the channel (the members of the list) should be able to play on their turn
this is achieved with checking the first position in the list and then popping it after their turn
i need to always check for a message being sent in the active game channels
but im using wait_for and not on_message because wait_for has a built in timeout
just check a list of the member ids and use an iterator ig

when did wait_for have a built in timeout?
long time ago haha
at the same time wait_for was added?
its pretty helpful
isPlayer = lambda message : message.author.id == client.players[message.channel.id][0]
message = await client.wait_for("message", check = isPlayer, timeout = 150)
yeah the docs straight up says by default it doesnt time out
does your game have to last a very long time? i.e. more than an hour or across bot restarts?
no it has to kick the player out of the list after 2 adn a half minutes
oh i misinterpreted your last message
How would you do it?
Hey there! Any hints where i can host my bots online 24/7?
Use the built in cooldowns?
You miss the point
The question was how to avoid the built in cooldowns resetting every time I reloaded the cog or the bot was rerun for some reason
Sure. I use AWS to host my bot primarily becuase I also have a dashboard and I need a domain, but google cloud, microsoft azure are all good
Ahh my bad, didn't see that bit
Would the way I suggested work as a temporary workaround?
I think that's the only way
The cooldowns are only going to be happening once per day anyway...
So it's not like it would be extremely inefficient
Oh if it's only once per day then yes for sure
Okay, cool
well anyway, you can just use wait_for in a while loop (and since your game is turn-based its easier to avoid race conditions with it)
When the user runs a command, fetch and check if the timedelta is over a day, is that what you're saying?
Yep, except I'm just using timestamps and seeing if the difference is greater than 86400
You know, discord.ext.tasks abstracts away that worry from you:
Awesome, ty! Is it hard to set up? Not really experienced with this stuff. What do you use aws ec2?
Is this referring to me?
User interface isn't very intuitive. Takes a bit to figure out what buttons do what and get the lay of the land, as it is
Yes, I'm not sure exactly how you could, but it seems like it might be helpful
Maybe, but I think just writing the times to the user in the db would work too
Another question if you don't mind
would that be within the slash command?
or do awaits work outside of an async
Yeah. Hard to tell which is more efficient on a day by day basis
!e
async def a():
...
await a()
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | SyntaxError: 'await' outside function
In that regard I like javascript
Also, if I want to self host, but I edit my code from another computer, how would I accomplish editing / uploading. For example, I code on my laptop, but that doesn't stay on 24/7. I want to host it on my PC.
Is there some application I would use to do something like this?
Yeah, you'd wanna set up github CI/CD
ugh yall got advance async
So pushing to github automatically validates it, and deploys it to your production server
arent coros in js called promises?
Yessir
ill make you a promise 
man at this point i have to do a proper rewrite of this bot
yeah just keep the while loop: wait_for in your slash command
JavaScript async 😔
Though it's kind of opposite it feels like. JS is normally async (at least it feels like it) so awaiting is like making it synchronoized
which is to be expected but 
what
const res = fetch(...);
return res;
returns undefined because it returns before fetching
easiest way to check for a list being empty?
Falsy
await fetch() right?
!e
x = []
if x:
print("List is not empty")
else:
print("List is empty")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
List is empty
Yes. Or .then()
oh cool
0, "", [], () all return falsey
await better 🗿
whats falsy?
promise chaining in JS fucks me over
just a false value
Something that is false
how do you thread an async function? cant find really something on the net
fetch(...)
.then(() => {
return ...;
});
but typescript doesn't like that so await is better
oh lol
yeah
Not quite
Something that is false-like, empty strings, 0, empty tuples, etc
!e print(bool(0)), print(bool([]))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | False
Ohhh, so not exactly False, but false in nature
not quite
Yep
Well a better way to put it would be something that evaluates to false
False value but not the False obj
That's what I said basically
Semantics of speech
i.e is is used for checking entities
I got the idea, thanks
!e
print(False is 0)
print(False == 0)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
003 | True
Going off what I said for it being False, it was interpreted as foo = False. The right way to say it is that the object is falsy because it is empty: foo = []
[] itself isn’t a Boolean
but has a bool value
^
does everything have a bool value?
like cheese its cheese but its made out of milk and its yummy
yes
cool
Is there a way to start tasks.loops not in setup ?
I also meant to mention. I'm running a small scale bot and dashboard, so I run my bot, a postgresql database, an API middleman for the bot and database, and the dashboard in itself. Also a domain from Route 53 and S3 as well, but that's beside the point. Not very scalable, but I plan to migrate them all to their own instances and set up a load balancer in front, and move the database to AWS RDBMS.
!e
print(bool("")), print(bool("string")), print(bool([])), print(bool([1, 2]))
etc
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | False
002 | True
003 | False
004 | True
Ignoring exception in command 'play2':
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 457, in _invoke_with_namespace
return await self._callback(self.binding, interaction, **values) # type: ignore
File "C:\Users\culan\OneDrive\Desktop\echo slash\cogs\testmusic.py", line 524, in play2
await interaction.response.send_message(embed=[song])
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 595, in send_message
params = interaction_message_response_params(
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 485, in interaction_message_response_params
data['embeds'] = [embed.to_dict()]
AttributeError: 'list' object has no attribute 'to_dict'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 998, in call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 476, in _invoke_with_namespace
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'play2' raised an exception: AttributeError: 'list' object has no attribute 'to_dict'
``` any thoughts on this I'm unaware of how to fix it
oops
embed is a list
!e print(False != (False or (True and False)) and True)
@slim ibex :white_check_mark: Your eval job has completed with return code 0.
False
ik but what did i do worng
What.
bro i just told you
You said in bed was a list doesn't exactly tell me what I did wrong
bro
you tried to use an attribute that doesn't belong to lists
you did exactly what okimii stated - by putting [] square brackets around the song variable, you've enclosed it in a list object
embed is literal to a list object
["im in a list"]
thats how python works variables are literal to there values and functions are literal to there return type
just remove the brackets
So get rid of the brackets? Because it's only one embed?
"im not in a list"
what
well you're using the embed= kwarg, so it expects a single embed
await interaction.response.send_message(embed = song)``` so this?
data['embeds'] = [embed.to_dict()] AttributeError: 'list' object has no attribute 'to_dict'
is hes error stating embed is a list but yes the return type of to_dict is a dict so hes just closing a dict inside of a list
embeds=[song] is probably what you intended if you wanted to pass your song embed in a list
^ that's the error....
list casting!
I didn’t see the rest of the trace back 💀
AttributeError: 'list' object has no attribute 'to_dict'```
That's why I just had
ok you either write embed=song, or embeds=[song]
curious, what does it mean when it says Ignoring Exception in commmand?
The one with the brackets is the one that's giving me the problem and the one that I just had in
just an exception on a command
It just is the exception raised from the command
Why is it ignoring it?
so your bot doesnt stop running


