#discord-bots
1 messages · Page 1148 of 1
created_at is a datetime.datetime object.
you'll be using .astimezone on it for your timezone
import discord
from discord import Intents
from discord.ext import commands
import os
discord_token = "..."
client = commands.Bot(command_prefix=";", intents=discord.Intents.all())
client.remove_command("help")
@client.event
async def on_ready():
print(f"The One and Only, THE {client.user} HAS JOINED")
client.command()
async def load(ctx, extension):
client.load_extension(f"cogs.{extension}")
client.command()
async def unload(ctx, extension):
client.unload_extension(f"cogs.{extension}")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
initial_extensions=[]
for xname in os.listdir("./cogs"):
if xname.endswith(".py"):
initial_extension.append(f"cogs.{filename[:-3]}")
print(initial_extensions)
client.run(discord_token)
Traceback (most recent call last):
File "/Users/boogytoogy/Desktop/discord-bots/sea-soft-bot/sea-soft-bot.py", line 24, in <module>
for filename in os.listdir("./cogs"):
FileNotFoundError: [Errno 2] No such file or directory: './cogs'
Why do I get this error and how do I fix it please?
what does your directory look like?
also, it's @client.command(), not client.command()
rip
using this to get an message by its ID only works if the message is in the channel i used the command in, is there a way that it can work for messages in other channels too?
await interaction.channel.fetch_message(ID)
To me looks like you either need to change it to ./sea-soft-bot/cogs or move cogs up a level.
in a message.listen event, does message.channel_id not work?
It should
Without getting current loop?
whenever i run my code it runs discord.py 1.7.3 even though i've installed 2.0, can anyone help please?
https://paste.pythondiscord.com/ujifaligiy (full embed code in case needed) - blah, I am lost with my wait_for block.
print('it works here 1') ## makes it up to here, shows in console.
# Stops working here. Error handle/trace back isn't picking anything below up so its like its non-existent.
reaction = await bot.wait_for("reaction_add", check=lambda reaction, user: user == reaction.message.id == msg.id)
if reaction.emoji == '👍':
CSGO = ctx.guild.get_role(780182144747569193)
await bot.add_roles(CSGO)
if reaction.emoji == '😀':
WF = ctx.guild.get_role(780244861130768395)
await ctx.add_roles(WF) ```
I currently have this wait_for block in my code, which isn't even being read at all, not by my error handler, no trace backs, nothing. I am pretty lost with it now, if anyone could help I would much appreciate it 🙂
Are you using replit? I have heard of this happening on there
No, I’m using pycharm :/
You should probably just use a on_raw_reaction_add instead of a while True with an event
The problem is mostly that we've uninstalled discord.py completely and reinstalled discord.py by using the git install from discord.py, yet it's still picking up discord.py 1.7.3 for him instead of v2.0
hello i want to ask if its possible to add buttons on published annoucements messages on the server following the channel.
^^
v2.0 is still beta. Not released yet
You think?
Wow, tell me something i dont know
Would I then need to run the embed command in my discord, and get the message id so the on raw event can find the correct one? Or is there a way I could reference the embed on post in the event for on raw reaction add?
Actually scratch what I said. I assumed you were making a reaction role sort of thing
Buttons are more suited for this
It is, but your idea does sound better.
If I'm to guess, this is what's wrong: check=lambda reaction, user: user == reaction.message.id
You're comparing a discord.User object with a int
Which will always be False
Oh, i wouldn't know how to rectify that bit, I have been trying for a few days since someone told me ^^
The larger problem there is you trying to compare a user to a message
Can you explain to me what you're trying to check for?
💀
So when the embed posts, the bot adds 5 reactions, the check is suppose to be for "reaction_add" so then if for example reaction is 👍 the bot check to see if a user reacts to said emoji, so it will then use that emoji to give the role by ID.
Well, that is what I am trying to achieve, but as you can tell.... Failing 🙂
Yes, okay. The biggest problem here is the check.. it's quite flawed
i've uninstalled discord.py completely and reinstalled discord.py by using the git install from discord.py, yet it's still picking up discord.py 1.7.3 instead of v2.0 (pycharm)
The 2 things you need to compare is that the user who made the reaction (user) is the same person who triggered the command. (ctx.author). You'll also want to check if the message the user reacted on (reaction.message) is the same as the embed message (msg)
Summary:
- Check if
ctx.author == user - Check if
reaction.message == msg
You can also shorten this entire thing
if reaction.emoji == '👍':
CSGO = ctx.guild.get_role(780182144747569193)
await bot.add_roles(CSGO)
if reaction.emoji == '😀':
WF = ctx.guild.get_role(780244861130768395)
await ctx.add_roles(WF)
if reaction.emoji == '🤓':
LA = ctx.guild.get_role(947231964753170473)
await bot.add_roles(LA)
if reaction.emoji == '😆':
CHILL = ctx.guild.get_role(896853904384458772)
await bot.add_roles(CHILL)
if reaction.emoji == '💪':
WH = ctx.guild.get_role(896882687816630293)
await bot.add_roles(WH)
by using a dictonary mapping of the emoji to the role ID
How can i make competing status?
it gets it internally
!d discord.ActivityType.competing
A competing activity type.
New in version 1.5.
@sick birch any ideas?
@devout iris for more info check the most recent pin which is mine 
Pycharm has a venv they create for you, there might be a problem with it being installed in the wrong venv
even if uninstall discord.py from the interpreter and then reinstalling it with this: pip install git+https://github.com/Rapptz/discord.py
doesnt seem to pick it up
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
oh so using pythin -m pip install would b better?
its not a status but an activity
Okkie
ahhh yess tysm
👍
ik yall dont help with music yt but is there a way for spotify i seen it on their page
reaction roles should be replaced by dropdowns 
look at the most recent pin of the channel it has a gist which has an example
Ares
sorry i saw it now lol
its fine no need to ask for forgiveness
👍
Don't believe so
Ok cheers for the advice, I'll take a further look into this tomorrow, tad late now! 😄
i think spotify doesnt like when bots stream music from their platform
i don't really chat here because i already got 2 warnings and who knows how mods gonna ban me
so i'm lurking and steal ideas
just follow the rules
i always do, i still don't think i did anything wrong
not exactly
theyre the same thing
invisible is when youre online but you want to appear offline, the different is one is intentional
i see but they are same on bots, right?
invisible is for bots
offline is for members iirc
ah alrighty
hello i invited my bot to a discord server and now it wont reply qwith my commands
nor in the server it was in? its on its not giving errors all commands worked 4 hours ago now it isnt
bot = commands.Bot(
command_prefix=discord.ext.commands.when_mentioned_or("i!", "hey bot ", "İ!", "Hey bot " "göster "),
intents = discord.Intents.all()
status = discord.Status.idle,
activity = discord.activity(
type = discord.ActivityType.competing, name = "asdsad"
)
)
where is the bracket error?
in mention_or
you missed a coma
i invited my bot to a discord server and now it wont reply with my commands, nor in the server it was in? its on its not giving errors all commands worked 4 hours ago now it isn't*
lmfao
i wasn't coding since a few months ago, a lot of things changed i guess
im using the bot commands in my server it would work on at 4:20pm its not 5:19pm but now it just isnt doing nothing?
my old codes are not good working ehehe
does anyone know?
yup activity lower case is a file
Which the Activity class is inside of
how does it now not work?
so confused
ah ok
could you send slash commands docs?
👉 👈 any discord wrapper based around threading
does anyone know abt the problem im having like i have 0 clue how to fix
@commands.command()
async def gallery(self,ctx):
embed=nextcord.Embed(color=0xfd9fa1,title="Server Gallery")
embed.set_image(url="https://imgur.com/a/ZDQGmSp")
embed.add_field('Icon by @ebon topaz')
await ctx.send(embed=embed)
im trying to make an embed thats basically
(image)
image description
(image)
image description
could someone help me?
embeds can only have one image
so my bot isnt working anymore for whatever reason and i removed all the code except for one line (help) and obv kept the stuff to make it work and i did the help command >>help and it still wont work
i dont know how but my bot is just completely not working at all it turns on but once you do a command (no errors help works it just doenst work anymore)
the token is right obv it has the permissions to speak just nothings working
out of no where
we cant really help if your problem is 'it doenst work'
anyone know how to use a webhook bot to send messages via python?
well yes but idk how to put it my guy like i said i left to the store with all my commands working came back an hour later now no command reply back as the bot doenst send any messages or give an error
show the code
theres a lot.
ill show you tho i removed all commands except help and it still doenst wokr (token is correct i did reset though)
you want me to paste 1000 lines of code?
I mean I dont know how to help you otherwise
alright
heres this tho
basically what i did was remove any other commands (all other code) and just try to see why it wont send any commands (>>cat >>help etc)
might not wanna share your token but aight
imma reset
oh lmao u said in vid aswell
i do get this though,
but idk if that makes every other who knows 50+ commands not work
im just more confused on how i go to the store come back and nothing works just baffled on it
can you paste the code so I can read it through
oml i hate formatting while typing i keep accidentally clicking enter
How would i make it so that the bot will wait for a message by a specified user that isnt the user who executed the command? Ive tried this and a few variations but it doesnt seem to work
def check(m): return m.author == self.bot.get_user(userid) and m.channel == ctx.channel try: message = await ctx.send(f"message") response = await self.bot.wait_for('message', check=check, timeout=30.0) except asyncio.TimeoutError: await message.edit(content = f"message") return
Edit: Found it, just made it use the user id, but the reason it wasnt working before is one was a string and one was an int lol
there ya go @deep mirage
do no commands work?
none!
nothing works
tried like all commands no errors nothing just simply doesnt work
anyone know how to use a webhook bot to send messages via python?
Ive ran your code and it works for me, I got no clue why yours isnt working
maybe it doens thave permissions to speak or doesnt have the right intents enabled
fr???
ok so. hm well let me try giving it permissions for everything
it has admin in the server i was using it on
then it just stopped
i gave it all perms ill try again
is it even possible to make money from a discord bot?
yea i gave it all perms including admin just it isnt sending the messages?
ive even tried a different bot with the discord portal
why is this doing this?
havent had this before trying to make a new bot
@deep mirage i invited it to my server it has admin etc the permissions just still not working?
any errors? what dpy version are you using?
how do i check that
print out discord.__version__
in your code
btw idk if you seen but at 4:19pm it was working i came back an hour later from the store then it didnt
print(discord.__version__)
do you have message content intents enabled?
yes
in your code too?
well i should since it worekd an hour earlier because i didnt remove anything when i was at the store
could you check?
either discord.Intents.all() or ```py
intents = discord.Intents.default()
intents.message_content = True
or any other variation of ti
i do not
then that's probably why your bot isn't working
do i just add intents = discord.Intents.default()
intents.message_content = True into the code
yes, and you pass in intents to the corresponding kwarg in your bot constructor
make sure you've passed the intents to the intents kwarg in your bot constructor too
how do i do that?
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.
im using client = commands.Bot(command_prefix='>>', case_insensitive=True,)
idk if that matters
nope, doesn't matter
alright
although you should generally name your bot instances bot instead of client to prevent confusion
no, don't instantiate 2 different bot classes
yea i thought so. should i just put intents=intent right after the case_insensitive=True, part
sure
you're using intents before defining it
there ya go. Restart your bot and see if you can use commands again
on a side note, you can pass help_command=None to your bot constructor (same way you did with intents) instead of calling remove_command
yoo it works thanks Lee! your the guy
glad to help :)
Anyone know when i add reactions how I can prevent it from bugging out because even if I unreact or react to both it'll display 2 even though theres only 1
that's a discord issue?
oh alright
Which library do you use?
Whats the best library to use?
Most libraries are good, and which one is the best depends on your personal preference, really
I just want recommendations if you dont mind
discord.py disnake hikari nextcord
Tysm
anyone online who has a good and in-depth understanding of error handlers and making them work in a custom way?
and that can help me privately until we've figured it out together
question, will trying to add a role to a member if they already have that role raise an error
just or pass it naturally
👍
is it possible that I can make my bot respond to both prefixed commands and slash commands?
Yes, hybrid commands!
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
hello guys why it dont give another guys role?
@commands.command(name="giverole")
@commands.has_permissions(manage_roles=True)
async def giverole(self, ctx: commands.Context, target: discord.Member, atomic, roles):
await target.send(f"you have get {roles} in a server ")
await target.add_role()
await ctx.send(f"{roles} gived to member :white_check_mark:")```
await target.add_roles(roles)
What is that atomic for?
if you want the role to be added no matter the state of cache iirc
Ya
oh wait you were asking for that random argument in his params lol
and if it will be passed to the argument in Member.add_roles it should be annotated with bool
how do I take my bot offline from heroku?
Turn off the host
where
there is something called maintenance mode. but turning it on doesn't do anything
it does it scales down the dyno
File "lisa.py", line 5, in <module> bot = commands.Bot(command_prefix=(['li ','Li ']),help_command=None) TypeError: __init__() missing 1 required keyword-only argument: 'intents'
what even
you need to pass in intents
intents = discord.Intents.default() # choose the one you want
bot = commands.Bot(..., intents=intents)
oh okay
do i need to do the same for discord.Client()?
yes
what’s the easiest database to learn for storing user data/info
For example
User ID: 913438773478559754 | Creation Date: Thu, 25 Nov 2021 14:39:34 UTC | Flag: 0.88 | Flags: Raiding, Failed Verification, ‘5’ Bans
how much info do u need to store
like many members or
does anyone have an example of a bot created with hybrid commands?
a lot of members
any sql base db would be good
it depends how big the bot gets
for production postgresql is the best and for like a provite or tiny in size bot sqlite would be good, remember to use asynchronous drivers depending on the database
hm
how about a database that responds back fast
okimii, you got experience with pymongo by any chance?
sql based dbs are pretty fast
are they web based or can be hosted locally
nah ive never touched mongo, ive only worked with sql based dbs
fair fair
by that i mean like is it just a file on my computer or do i need to have a website for it
sqlite uses files to store data so no need for hosting
YEY
!pypi aiosqlite
is mongodb any better?
sql is better imo
im using mongo rn for a project and not enjoying it
sql's syntax quite basic and can be used with many languages and most companies use sql based dbs like postgresql
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
sqlbolt is where i learned sql, its quite a good course
was it possible to get one of the command parameter in a custom checks?
like a functions params?
yeah
!d inspect.getargspec
inspect.getargspec(func)```
Get the names and default values of a Python function’s parameters. A [named tuple](https://docs.python.org/3/glossary.html#term-named-tuple) `ArgSpec(args, varargs, keywords, defaults)` is returned. *args* is a list of the parameter names. *varargs* and *keywords* are the names of the `*` and `**` parameters or `None`. *defaults* is a tuple of default argument values or `None` if there are no default arguments; if this tuple has *n* elements, they correspond to the last *n* elements listed in *args*.
Deprecated since version 3.0: Use [`getfullargspec()`](https://docs.python.org/3/library/inspect.html#inspect.getfullargspec "inspect.getfullargspec") for an updated API that is usually a drop-in replacement, but also correctly handles function annotations and keyword-only parameters.
Alternatively, use [`signature()`](https://docs.python.org/3/library/inspect.html#inspect.signature "inspect.signature") and [Signature Object](https://docs.python.org/3/library/inspect.html#inspect-signature-object), which provide a more structured introspection API for callables.
not sure if theres a better way tho
so it should be smth like:
def custom_check():
def predicate(ctx):
inspect.getargspec(predicate)
ive personally never used a custom check but if its a deco you can just use the argument that is used to pass a function
custom checks are a little weird, dunno if it works, they're something like this:
from discord.ext.commands import check
def custom_check():
def predicate(ctx):
#your stuff
return check(predicate)
well here it doesnt seem like the function arg is being used so you probably can put it to work
commands.check just checks what the inner functions boolean value returns and then probably sets the check internally, not sure on how its done
!d discord.ext.commands.Context.args
The list of transformed arguments that were passed into the command. If this is accessed during the on_command_error() event then this list could be incomplete.
interesting attr
thanks
raise TypeError(f"Cannot instantiate {self!r}")
TypeError: Cannot instantiate typing.Any
``` but wtf does this mean 
AnyContext = Any(Context, ApplicationCommandInteraction)
from typing import TYPE_CHECKING, Any, Optional
if TYPE_CHECKING:
from ....launcher import PrivateTicketBot
i've only added this section of code 
That's not how you use Any
You want Union[Context, ApplicationCommandInteraction]
did he just try to initiate Any???😭
instantiate
whats the difference?
Lmao don't ask me why but the fun fact is that it worked yesterday
iniating => starting something, instantiating -> creating an instance of something
you sure you werent dreaming🛌
pretty sure
well you would need to initiate an object to instantiate it?
parenthesising 😳
okimii im the indian here ur supposed to be good at english
🥸
Btw with disnake i'll have to use ApplicationCommandInteraction.filled_options
hi zeffo
👋
huh i didn't know that 👀
allot of regulars are indian here, hun bun, sarth boo, zeffo and other very knowledgeable people
nova
who
oh wait nova got banned

how tf u forgot nova
@slate swan
yeah
!e ```py
import sqlite3, datetime, time
conn = sqlite3.connect(":memory:")
current = datetime.datetime.now()
conn.execute("CREATE TABLE test ( timestamp BIGINT )")
conn.execute("INSERT INTO test VALUES ( ? )", (current.timestamp(),))
conn.commit()
after some time
time.sleep(5)
c = conn.execute("SELECT * FROM test")
timestamp = c.fetchone()[0]
old_time = datetime.datetime.fromtimestamp(timestamp)
print(datetime.datetime.now()-old_time)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
0:00:05.045057
^ this is how you can save timestamps and get the time user was afk for
the code won't work if you just copy paste it so make your own.
Thanks i just need to know starategy
ic add me to that list as well
the Indian one not the knowledgeable one 😂
Is there any way to remove microseconds from it?
!d datetime.datetime.seconds use this to get only seconds
wtf 1 minute
!d datetime.timedelta.total_seconds
timedelta.total_seconds()```
Return the total number of seconds contained in the duration. Equivalent to `td / timedelta(seconds=1)`. For interval units other than seconds, use the division form directly (e.g. `td / timedelta(microseconds=1)`).
Note that for very large time intervals (greater than 270 years on most platforms) this method will lose microsecond accuracy.
New in version 3.2.
Ok
import datetime, asyncio,time
async def main():
current = datetime.datetime.now().replace(microsecond=0)
times = current.timestamp()
time.sleep(5)
timestamp = times
oldtime = datetime.datetime.fromtimestamp(timestamp)
nowtime = datetime.datetime.now().replace(microsecond=0)
pr = nowtime-oldtime
print(pr)
asyncio.run(main())
I did this and worked
noice, you didnt need asyncio for this btw
😔 ☹️
Yes I live in india
lucky, i wish i lived with hun bun or sarth boo😔
hun bun

Nice nick
ikr
0-0 thats something i didnt know as well
hunter is gonna be mad well not like he is online anyway
hey guys, question
i got a bot that has two files:
file1.py
import discord
import time
import random
client = discord.Client()
@client.event
async def on_message(message):
if message.content.startswith("$rps"):
with open("games/" + game + ".py", "r") as f:
exec(f.read())
and a second file
rock paper scissors.py
import random
@client.event
async def on_message(message):
random_number = random.randint(1, 3)
if message.content == "$START":
await message.channel.send("Rock, Paper, Scissors! (To exit, say $EXIT)")
await message.channel.send("Type $rock, $paper, or $scissors to play!")
if message.content == "$rock":
if random_number == 1:
await message.channel.send("I chose rock, it's a tie!")
#blah blah blah more code stuff
when i launch the game with $rps, it only responds to the commands in rock paper scissors.py and i don't know how to stop running rock paper scissors.py without stopping file1.py ...
is there a way to stop it or something?
use a listener instead of an event
nvm Client doesn't have it
rip
instead of manually parsing commands like this I would recommend using the commands ext instead
well i kinda have 500 lines of code so unless it's necessary i don't think i can do it
(but ofc it it'll make it work i will)
the thing is, using commands.ext will reduce the amount of messy and 🍝 code
import discord
c = discord.Client()
@c.event
async def on_message(message):
if message.content.startswith("!ping")
await message.reply("pong")
``` ```py
from discord.ext import commands
b = commands.Bot(command_prefix="!")
@b.command(name="ping")
async def ping(ctx):
await ctx.send("pong")
``` you can decide what looks cleaner and easier
try doing what it says
!rule 7
python -m pip install --upgrade pip
Hiii zeffo 
Thanks bro
np
Hello, I was wondering, has anyone messed with the select menus? I need some help... Is there a way I can not have the menu die after a certain amount of time?
Is there a time out or something?
the default timeout is 180 sec
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
set the timeout to None
# if subclassing
class MySelectView(ui.View):
def __init__(self):
super().__init__(timeout=None)
#if not subclassing
view = ui.View(timeout=None)
so much effort ashley 🙏
and you still ignore my greetings, fml 
OH, it's the view, ight, thank you @slate swan and @vocal snow :)
it still doesn't work, how do we reinstall the pip?
Quick yes or no.
Can Cog names have aliases?
If not is there anyway for the help command to use different languages for it?
check your pip version
do you know the command to see the version?
pip --version
Just to clarify, you want to create aliases for the helpcommand?
No i mean Cog names
like say the catergory
where commands are stored
like:
Why would you need that?
Yes, but where would the cog aliases be used?
Are you going to access them in a custom help command?
yes because ignoring messages are a serious federal offense
Hunter already know that I live in india
I don't think there's built-in support for this. You can define an 'aliases' attribute in the cog and then use it in a custom help command though
Hmm mk then, thank you
meow = int(joingwbutton.joinwbutton.label)
meow -= 1
joingwbutton.joinwbutton.label = str(meow)```
it tells me i cant call a function but im just calling a param of it that i need to change which is the label
not for that for hun bun
i got goosebumps saying that
beware Hunter
since that name is only allowed till okimii
Probably a stupid question, but can you get the message a view is attached to in the view object? (sub classing)
For context, I want to basically remove the view to remove itself when it times out
yeah, do interaction.message it'll return a Message obj
where interaction is an instance of Interaction
won't be possible to do that within the view
damn, ight thanks
I mean, I got it to work, but it's very stupid and work-around-y
why not? just remove it from self.message (assuming atleast one interaction is done)
class VoteView(disnake.ui.View):
def __init__(self, message: disnake.Message, **options):
self.message = message
super().__init__(**options)
async def on_timeout(self) -> None:
print("OMFG IT HAPPENED, THE VIEW IS DEAD!!!")
await self.message.edit(view=None)
msg: disnake.Message = await inter.channel.send(content="Huh, what's going on?")
view = VoteView(msg)
await msg.edit(view=view)
class VoteView(disnake.ui.View):
message: disnake.Message
def __init__(self):
super().__init__(timeout=60)
async def on_timeout(self) -> None:
# times out after 60 seconds
self.stop() # stops buttons from being active
await self.message.edit(view=None) # removes buttons from message
view = VoteView()
view.message = await inter.channel.send(content="etc etc", view=view)```
This would work fine, bit neater
ew
how and where is it getting the message though?
and funny enough, just wrote something like that
view.message = ...

error ```py
SyntaxError: Non-UTF-8 code starting with '\xe1' in file D:\New folder\pythonProject\main.py on line 42, but no encoding declared; see https://python.org/dev/peps/pep-0263/ for details
code
```py
@bot.command()
async def stonks(ctx):
main_embed = discord.Embed(title="`'*•.¸♡ 𝒲𝑒𝓁𝒸𝑜𝓂𝑒 𝒯𝑜 𝐸𝒸𝓈𝓉𝒶𝓈𝓎 ♡¸.•*'`", description="♡ • 𝒜𝓃𝒾𝓂𝑒 • 𝒮𝑜𝒸𝒾𝒶𝓁 • 𝒟𝒶𝓉𝒾𝓃𝑔 • 𝐹𝓊𝓃♡ \n ꘎♡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━♡꘎ \n ˗ˏˋ ♡ ˎˊ˗ ʟᴏᴏᴋɪɴɢ ꜰᴏʀ ᴀɴ ᴀɴɪᴍᴇ, ᴅᴀᴛɪɴɢ, ꜱᴏᴄɪᴀʟ ᴀɴᴅ ᴄʜɪʟʟ ꜱᴇʀᴠᴇʀ ᴡʜᴇʀᴇ ʏᴏᴜ ᴄᴀɴ ᴍᴇᴇᴛ ᴏᴘᴇɴ ᴍɪɴᴅᴇᴅ ᴘᴇᴏᴘʟᴇ ᴡʜᴏ ꜱʜᴀʀᴇ ᴛʜᴇ ꜱᴀᴍᴇ ɪɴᴛᴇʀᴇꜱᴛꜱ ᴀꜱ ʏᴏᴜ? ɪꜰ ʏᴏᴜ ᴡᴇʀᴇ, ʏᴏᴜ'ᴠᴇ ꜰɪɴᴀʟʟʏ ꜰᴏᴜɴᴅ ᴡʜᴀᴛ ʏᴏᴜ ᴡᴇʀᴇ ʟᴏᴏᴋɪɴɢ ꜰᴏʀ ˗ˏˋ ♡ ˎˊ˗\n ೃ⁀➷ Here's What we Offer: ೃ⁀➷\n ʚɞ Ecstasy is a casual and chill server, the main purpose of the server is for you to have someone to talk and spend time with. You can meet many new people, make new friends and perhaps even find yourself a date or partner.\n ʚɞ We have chill staff, and an amazing atmosphere where you'll be able to fit in and meet people just like yourself.\n ʚɞ We have many bots to entertain you, for example, mudae, dank-memer, truth & dare and many more!\n ʚɞ LGBTQ+ supporting and accepting server.\n ʚɞ Friendly and SFW server\n ʚɞ We'll make sure you never feel lonely again <3.\n ˚ ༘♡ ⋆。˚ 𝒮𝓉𝒾𝓁𝓁 𝓃𝑜𝓉 𝒸𝑜𝓃𝓋𝒾𝓃𝒸𝑒𝒹? Join now and see for yourself! ˚ ༘♡ ⋆。˚",color=0xE6E6FA)
view = stat()
await ctx.send(embed=main_embed,view=view)
return
A character in there isn't within the UTF-8 character range
I'd assume it's probably one of those "fonts"
regarding music bots, what's exactly the autoplay mode? It tells the bot to fetch tracks from some history after the queue is empty?
I believe autoplay is simply the existence of a queue feature
What’s the most accurate way to find a user’s account creation date/time down to the millisecond
!d discord.User.created_at
property created_at```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
That's what the api gives, so it should be the most accurate
code
Anyway i fixes
nice
It working
try ctx.message.add_reaction
no
its an interaction, not an context
the message you send on discord is not a discord.Message, its a webhook here which doesnt have a add_reaction method
that depends on the library you're using
@slate swan how to fix this?
hello, which is the "best" way to code discord components? Surfing through the internet I found many libraries. Which one is the best? Talking about code flow and efficiency it seems to be "from discord import Button"
supposed to be strftime
what you trying to do
strptime is also a thing
Do I have to use Rapptz version?
.
You literally asked 2 minutes ago. discord.py is the go to, but find what you prefer, not what people say.
maybe they used strptime on datetime module instead of datetime.datetime object then
rapptz version? 
discord.py's master branch (version 2.0), 3rd party libraries are no longer maintained are they mess with discord.py internals which is bad.
perfect
But why mine not working?
show code..
@bot.event
async def on_message(message):
userid = message.author.id
connection = bot.connection
cursor = await connection.cursor()
await cursor.execute('SELECT * FROM afktable WHERE user_id=?',(userid,))
check = await cursor.fetchone()
if check == None:
pass
else:
timess = await cursor.execute('SELECT time FROM afktable WHERE user_id=?',(userid,))
timestamp = (await timess.fetchone())[0]
await cursor.execute('DELETE FROM afktable WHERE user_id=?',(userid,))
await connection.commit()
oldtime = datetime.datetime.fromtimestamp(timestamp)
nowtime = datetime.datetime.now().replace(microsecond=0)
pr = nowtime-oldtime
t = datetime.strptime(pr,"%H:%M:%S")
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
ans = humanize.naturaldelta(delta)
embed = discord.Embed(title=f"{message.author}\nAFk removed!", description=f"I have removed your AFK\n you were afk for {ans} ",color=discord.Color.green())
embed.set_thumbnail(url=message.author.display_avatar.url)
await message.channel.send(embed=embed)
await bot.process_commands(message)
Hmm
should be datetime.datetime.strptime()
Ok
you can also pr.strptime directly no its a timedelta
i doubt if even datetime.datetime.strptime would work, timedelta's cannot be formatted using that method
Nope, but you can use an invisible character to do that
Yeah sure
oh nvm i misunderstood the question lmao
I have one problem in comamnd
When i type >afk playing game
My bot only takes first word as reason playing
How can I do my bot takes full line?
async def command(ctx,*, argument):
...
Btw i saw that sirlancebot when i type wrong name of comand it suggests me did you mean <command name>?
How can I make that?
lmao word similarity and machine learning
How tho?
use fuzzywuzzy
!pip fuzzywuzzy
difflib may work too
difflib works quite well yeah
Very hard 🥵
it's not hard
Its hard 🔥
just combine every command name and aliases and then compare the input with difflib.get_close_matches()
I Mena that when i use comamnd it gets name error how would it know it?
you would be utilising the on_command_error event, check if the instance of exception was commands.CommandNotFound, and then do the string comparison task inside that
!d discord.ext.commands.Context.invoked_with gives you the command name which was used
The command name that triggered this invocation. Useful for finding out which alias called the command.
note that ctx.command would be None here
How can I use this command invoked with
use it like a normal attribute
I never used such
Any short example please?
@bot.listen("on_command_error")
async def error_handler(ctx, error):
invoked_with = ctx.invoked_with
matches = difflib.get_close_matches(invoked_with, command_names_and_aliases)
``` easy, right?
!d discord.ext.commands.Bot.commands
property commands```
A unique set of commands without aliases that are registered.
activity = discord.Activity(type=discord.ActicityType.watching, name="TelSpin")
AttributeError: module 'discord' has no attribute 'ActicityType'
there are command objects btw
ActivityType
Ohhh thk
@commands.dynamic_cooldown(bucket, retry_after, self._buchets.type)
AttributeError: module 'discord.ext.commands' has no attribute 'dynamic_cooldown'
it is just cooldown
you're not using 2.0
!d discord.ext.commands.dynamic_cooldown boo
@discord.ext.commands.dynamic_cooldown(cooldown, type)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Cooldown "discord.app_commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
yes, it can be used when you want to return a different cooldown for different bucket
!d disnake.ext.commands.dynamic_cooldown
@disnake.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Command "disnake.ext.commands.Command")
This differs from [`cooldown()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.cooldown "disnake.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`disnake.Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message") and must return a [`Cooldown`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.Cooldown "disnake.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.BucketType "disnake.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CommandOnCooldown "disnake.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.disnake.ext.commands.on_command_error "disnake.disnake.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
New in version 2.0.
exists in disnake too, while it was forked
it has always been in dpy 2.0...

uhm i dont understand what i should do lol
yup
alr cool
How can i make add to server button?
go to your bot's Oauth2 , select General ,
default auth link ..
Oh ty
This is connected with Mongo db, why doesnt this work?
@commands.command(aliases=["bal"])
@cooldown(1, 2, BucketType.user)
async def balance(self, ctx, user: discord.Member = None):
""" Check your balance"""
if user is None:
user = ctx.author
try:
bal = await ecomoney.find_one({"id": user.id})
if bal is None:
await self.open_account(user.id)
bal = await ecomoney.find_one({"id": user.id})
embed = discord.Embed(
timestamp=ctx.message.created_at,
title=f"{user}'s Balance",
color=0xFF0000,
)
embed.add_field(
name="Wallet",
value=f"${bal['wallet']}",
)
embed.add_field(
name="Bank",
value=f"${bal['bank']}",
)
embed.set_footer(
text=f"Requested By: {ctx.author.name}", icon_url=f"{ctx.author.avatar_url}"
)
embed.set_thumbnail(url=user.avatar_url)
await ctx.send(embed=embed)
except Exception:
print(f"{bal}")
await ctx.send('An error occured')```
Ping me if you have an answer
"doesnt work" doesnt' explain anything.
how can i make a channel edit loop
like it edits the channel name every 1hr or so
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
you can use this
ecomoney
alr
bot = Bot() do i have to declare this everytime i end a class ?
how to add text to modal like an embed description
no? you just use the original one
alr
and can i like make smh like this
class ....
class ...
now the commands using both the class
cogs?
does Modal.description work?
not rn
idk lemme check
!d discord.ui.Modal
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
linter shows no such attribute either
i tried in the label for textinput but there seems to be a size limit
oh, ok hold on
sure np
can you even add text to modals lol
idk that's why i am asking ;-;
is there any roundabout way
what if i make another textinput modal and the write the text there🤣
idk, i have never used modals before
text input seems like the only way to add stuff to modals
v2 cogs example ?
Why doesnt it exept the else where it shows that he had lost?
@commands.command()
@commands.cooldown(1, 300, commands.BucketType.user)
async def slots(self, ctx, amount: int):
try:
user_bal = await ecomoney.find_one({"id": ctx.author.id})
if user_bal is None:
await self.open_account(ctx.author.id)
user_bal = await ecomoney.find_one({"id": ctx.author.id})
if amount > user_bal["wallet"]:
await ctx.send('You do not have enough money to gamble that much')
elif amount <= 0:
await ctx.send('You cannot gamble 0 or less')
return
final = []
for i in range(3):
a = random.choice([':apple:', ':lemon:', ':tangerine:'])
final.append(a)
await ctx.send(str(final))
if final[0] == final[1] or final[1] == final[2] or final[0] == final[2]:
await ctx.send(f'{ctx.author.mention} Du hast gewonnen! :) ')
await ecomoney.update_one({"id": ctx.author.id}, {"$inc": {"wallet": +amount}})
else:
await ctx.send(f'{ctx.author.mention} Du hast verloren! :(')
await ecomoney.update_one({"id": ctx.author.id}, {"$inc": {"wallet": -amount}})```
ping me if you have a fix
ty <3
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
...
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
and how would i load it from main.py ?
i entered the text i wanted to display in a textinput field
now i need a way to stop user from typing there preferably
no i set as default
placeholders don't give me enough character limit either
Gn all
gn
^
class MyBot(commands.Bot):
...
async def setup_hook(self) -> None:
for cog in cogs:
await self.load_extension(cog)
or
bot = commands.Bot(...)
async def load_extensions(bot):
for cog in cogs:
await bot.load_extension(cog)
bot.setup_hook = load_extensions
for more info check this out (https://gist.github.com/Rapptz/6706e1c8f23ac27c98cee4dd985c8120)
thanks
it shows error in cogs
like it says
thats just an example, you are not supposed to copy paste it as it is
cogs is an iterable which contains the the files which contain your cogs
ik that my folder is named as cogs
do os.listdir('cogs') then remove the .py from the name of the cogs before loading
so i made the cog outside the folder i.e. in the same directory with the main.py
and this
it wont load...
use brain
dont you think that it will overwrite the setup_hook only when the function is ran
Why doesnt it exept the else where it shows that he had lost?
@commands.command()
@commands.cooldown(1, 300, commands.BucketType.user)
async def slots(self, ctx, amount: int):
try:
user_bal = await ecomoney.find_one({"id": ctx.author.id})
if user_bal is None:
await self.open_account(ctx.author.id)
user_bal = await ecomoney.find_one({"id": ctx.author.id})
if amount > user_bal["wallet"]:
await ctx.send('You do not have enough money to gamble that much')
elif amount <= 0:
await ctx.send('You cannot gamble 0 or less')
return
final = []
for i in range(3):
a = random.choice([':apple:', ':lemon:', ':tangerine:'])
final.append(a)
await ctx.send(str(final))
if final[0] == final[1] or final[1] == final[2] or final[0] == final[2]:
await ctx.send(f'{ctx.author.mention} Du hast gewonnen! :) ')
await ecomoney.update_one({"id": ctx.author.id}, {"$inc": {"wallet": +amount}})
else:
await ctx.send(f'{ctx.author.mention} Du hast verloren! :(')
await ecomoney.update_one({"id": ctx.author.id}, {"$inc": {"wallet": -amount}})```
list = ['🍉', '🍋', '🍒', '🍇', '🔔', '🍎', '🪐']
how can i get a random element from that list?
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
nice logic btw
just check with if final[0] == final[1] and final[0] == final[2]
im trying to code a slot machine bot
so..
also i already found the answer, thanks
soooooooooooooo the question is irrevelant to the channel
can you handle me the answer?
hehe
Hey everyone, I have a discord bot I'm working on that tells people how much time they've spent in each voice chat, does anyone know how to get the name of a voice chat using the ID for the voice chat?
graphed retention across the 318 players who have played my discord bot game now... 50 depth is 15mins gameplay. the graph keeps getting worse and worse
you can use bot.get_channel(<id>) for the channel object and then use .name
depresso
ahh thank you very much!
Preparing wheel metadata ... error
Bound to happen eventually, unfortunately
Hard to keep any player retention for long with any game, really
replit?
most mobile games have an aim of around 10% for day 7 retention i believe
assuming one play session a day i've got like 0.4% 
A KeyError would mean that a key is not present in a dictionary
Preparing wheel metadata ... error ERROR: Command errored out with exit status 1:
are you sure the key is a string?
inbstalling discord 2.0
Have a try/except block to handle missing keys
Either that user id is not present in user_data or card is not a valid key for the data in user_data[userr_id]
brad 

Either add it, or handle when a key is missing
am I just invisible or everybody ignores me on purpose here
who u
show code
Add a check if the user id is in the user data dictionary, and if it is not, add it
A try/except block
Line 117
sorry
try:
card_num = str(user_data[str(userr.id)]["card"])
except KeyError:
card_num = 0
print("User not present in 'user_data'.")
Something like that could work
you could you just use get?
Since its a json object its a bit harder to try and add to it if there is no user already present
imagine capping
Try it and let me know
Yes
Because you have only one user in the json file you are checking
What do you think you should do
Thats a great idea
You tell me
You know that a json file can contain multiple entries right?
For sure, you will have to read and write to the json file
And you could check if a user id is present in the user data file, and if it is not, write to the file. But something like this can get messy very fast, and is why databases are used
Then this is a great chance to learn a bit about it
sqlite3 comes with python
I have used it once for a project of mine
I haven't made another project needing it
I also don't do bots all the time
Learn the basics of sqlite3, then if you're using it in tandem with a discord bot, use aiosqlite. If you already know sqlite3, migrating to aiosqlite should be a cake walk
The problem is reading and writing to the json file correctly
Does every member have their own card?
Oh
Yeah you are going to need every member
How else would it work?
Which follows a relatively simple pattern:
- load the contents of your JSON file into an in-memory python dictionary
with open("filename.json", "r") as f:
data = json.load(f)
- Make any changes
data[...] = ...
data[...] = ...
data[...] = ...
- Save the dict back into the JSON file:
with open("filename.json", "w") as f:
json.dump(f, data, indents=4)
You asked how to read/write into a JSON file?
this command is too error-prone with KeyError exceptions
JSON-as-a-db will usually always look like this
You need to add:
Step 1: a check if the user id is present in the json file
Step 2: if it is not present, create an entry, serialize it, write it out to the file
Step 3: if it is present, read the data and display it
What I wrote earlier could be used as a check:
try:
check = user_data[str(userr.id)]
except KeyError:
# add step 2 from above
# step 3 goes on
Another way:
if user_data.get(str(userr.id)):
# it exists
else:
# it doesn't
Thats the better way ^
Both are completely valid, though I suspect in your case it would end up looking like spaghetti code regardless
So perhaps a code refactoring is in order?
i'd suggest migrating to some sql based database like sqlite3 instead.
a "SELECT xp, level FROM table WHERE user_id = .."
looks much cleaner than ```py
xp = data[str(ctx.guild.id)][str(userr.id)]["xp"]
lvl = data[str(ctx.guild.id)][str(userr.id)]["level"]
Even better if you can throw an ORM in 😄
he can create a function
to make the code less redundant
How to add and remove emojies in a server with discordpy?
!d discord.Guild.delete_emoji
await delete_emoji(emoji, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") from the guild.
You must have [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
Changed in version 2.0: `emoji` parameter is now positional-only.
and add_custom_emoji for creating
nope, i have my entrance exams soon so.
json usually isn't too good of an idea as a db, no security risks but it's a little hacky iirc
forget about them😼
it isnt even a db lmao
because it can store data doesnt mean its a db but people do it 😔
no hehe.
😔
its a college entrance exam so i can't miss it
forget college
😼
how about forget you
not nice
ikr
@bot.include
@dawn.slash_command(
"avatar_test",
"check avatar of a user",
options=[
dawn.Option("user", "user to get avatar of", type=hikari.Member, required=False)
],
)
async def av_command(
context: dawn.SlashContext, user: hikari.Member | None = None
) -> None:
await context.create_response((user or context.user).avatar_url)
``` how's this command handler structure
i'll be renaming the include deco
the heck is SlashContext, and you should rename include to register or something
a slash command context ez..
you mean an interaction🧍
there's already like 4 class with interaction in hikari natively
i dont want it to sound anything similar
because this class will have an interaction property already
interaction.interaction is weird
Well your giving me pycord vibes so get away from me
it was pycord or some third party lib iirc it was discord_slash or something
in pycord its ApplicationContext
ands its useless
shhhhhhhh
because it just wraps the interaction object
maybe rename SlashContext to InteractionContext
that won't be specific to slash commands then
there's user commands and message commands too
slash arent the only app commands
i know
even better
idk if its just me but i read it like its the Context of the Interaction
¯_(ツ)_/¯
i need to read an article so name it whatever
What are the common ways to make our bot efficient and faster?
avoid useless requests, blocking code and practices which use less memory
strict typehinting, use mypy or something
mypyc can give it a performance boost
obvious difference
import datetime
start = datetime.datetime.now()
def add(num: int, num2: int) -> int:
return num + num2
for i in range(1000000):
add(1, 4)
print(datetime.datetime.now() - start)
``` code used for testing^
async def gallery(self,ctx):
galleryArray=[]
embed1=nextcord.Embed(color=0xfd9fa1,title="Server Gallery", description='Icon by @ebon topaz')
embed1.set_image(url = "https://media.discordapp.net/attachments/917184938690899971/996945126238728374/IMG_6075.png?width=663&height=663")
galleryArray.append(embed1)
embed2=nextcord.Embed(color=0xfd9fa1,title="Server Gallery", description='Banner by @compact oriole')
embed2.set_image(url = "https://media.discordapp.net/attachments/934002322151989339/934121005192974466/IMG_0361.jpg?width=1178&height=662")
galleryArray.append(embed2)
embed3=nextcord.Embed(color=0xfd9fa1,title="Server Gallery", description='Banner by @molten snow')
embed3.set_image(url = "https://media.discordapp.net/attachments/934002322151989339/934121154757672960/IMG_2881.png?width=1440&height=360")
galleryArray.append(embed3)
embed4=nextcord.Embed(color=0xfd9fa1,title="Server Gallery", description='Banner by @red lintel')
embed4.set_image(url = "https://media.discordapp.net/attachments/934002322151989339/934121300719464508/export202201181200317830.jpg?width=1178&height=662")
galleryArray.append(embed4)
embed5=nextcord.Embed(color=0xfd9fa1,title="Server Gallery", description="@unreal pasture\'s profile picture by @brave talon")
embed5.set_image(url = "https://media.discordapp.net/attachments/934002322151989339/934233925071568907/final.png?width=663&height=663")
galleryArray.append(embed5)
msg = await ctx.send(galleryArray[0])
await msg.add_reaction('⬅️')
await msg.add_reaction('➡️')
msg.on_reaction_add(self, reaction, user:nextcord.Member):
if reaction.emoji == "➡️" and msg!=galleryArray[4]:
await msg.edit(content=msg+1)
if reaction.emoji == "➡️" and msg!=galleryArray[0]:
await msg.edit(content=msg-1)
im trying to make an array of embeds where you can cycle through the embeds with the arrow reactions (just like Mudae bot)
can someone help me?
**Help me for this **
I have this error for 2 days i cant do anymore please
https://mystb.in/ChartRecallRonald.sql
?
alright thanks!!
bot.loop.create_task(<function>)
does this will create a loop for the function when the bot gets online (i have put it in on_ready() event ) or i have to put a while True in <funciton> ?
it will, but what version of dpy you are on?
you can usually just use bot.start() instead of bot.run() if you wanna do async stuff first
!d discord.ext.tasks.loop exists btw
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
lemme explain you my problem
I have a mysql database, and i tried connecting to it while running the bot, it worked perfectly and i can get data and display in discord. Tho when the db updates, it does not fetch the updated value, rather it fetch the old value
dont' use sudo
do you commit the data after writing?
i am using pycord for thread support
discord.py supports thread too.
it does?
uhh its managed by a java plugin, the database
i mean do you commit in the code?
oh i have written most of my code in pycord now
like after periodically?
nope, after writing data
it just writes constantly, the purpose of db is to store stats of people in a kitpvp server
so like idk when the data is written
as for now i came up w a very bad solution
use a discord.ext.tasks Task then
from discord.ext import tasks
@tasks.loop(seconds=60)
async def foo():
# do your stuff
...
foo.start()
this will execute the foo function in every 60 seconds
alright, thankyou!!
not work
` Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error
× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
`
How can I call a function whenever i stop the code or turn off the bot?
place it after bot.run()
it will get executed when you close the bot using ctrl+c in your terminal
oh alrightt
what's your device/server and python version
if you're using replit just create another repl
if you're on a debian based distro ```bash
$sudo apt install libffi-dev
now do the pip install cmd again
installed it but it still doesn't work
` Getting requirements to build wheel ... done
Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error
× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [61 lines of output]
running dist_info
`
how can i kick someone if they say something
just an example say that said "." then they should get kicked
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
check for . in message.content
you can use message.author to get the member and kick it
thank u
on_member_join?
Looks like for some reason interaction.guild is None, maybe because it's not cached?
I'm trying to set up the message content intent on disnake but I can't figure out through the docs how to enable it in the code
I tried this and also just creating intents and then settings it after but I can't seem to see it explained how to do it
intents = disnake.Intents(message_content=True)
client = disnake.Client(intents=intents)
Nevermind I figured it out
Instead of this
intents = disnake.Intents()
intents.message_content = True
client = disnake.Client(intents=intents)
You have to have this...
intents = disnake.Intents.default()
intents.message_content = True
client = disnake.Client(intents=intents)
im pretty sure message_content isnt a thing in disnake
!d disnake.Intents.message_content
Whether messages will have access to message content.
This applies to the following fields on Message instances...
Hmm it seemed to work when I just enabled it now 🤔
seems like it is implemented
same
The documentation on setting it up isn't great but maybe it's just been added in
yeah you would need to go through a class's attribute etc
Will it be like this
command_list = bot.commands
yes
Do it return. List or tuple
property commands```
A unique set of commands without aliases that are registered.
Neither, it's a set
So what do it return?
cursor.execute(f"SELECT user_id FROM eco WHERE user_id = {author.id}")
NameError: name 'author' is not defined```
confused
It's message.author.id
Try once
ok i have a new one
if message.author.client:
AttributeError: 'Member' object has no attribute 'client'```
A set of the commands.Command objects
do you know your datatypes, bro?
!d set
class set([iterable])``````py
class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.
Sets can be created by several means:
• Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`
• Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`
• Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
Can you help
Replit is always adding humanize package again and again even i have installed and my bot is starts slow
How would I add discord py 2.0 to a requirements file?
That's definitely a (new) dependency from an updated version of a package
a set
git+https://github.com/Rapptz/discord.py
there's no ETA, but the development is quite fast and they are catching up with the lastest Discord API features so maybe soon?
Hey guys
I am trying to import the library requests to grab some data from an api and then print that data through my py discord bot. However, when i try to import requests I get an error on repl saying: "Replit: Package operation failed."
Any solutions?
poetry add requests
I still get a type error
it seems to be only be an issue withimport requests too
importing json and other libraries is fine
the line asher told is a shell command you need to do in the terminal
not in your py file.
yes i know, and i still get an error
what's the exact error
use aiohttp instead, if in an async context eg. almost every discord bot lib ever
i created a new repl file and deleted some env files. now i am able to import requests, weird. anyway, thanks for the help all
Totally a replit issue.
Hi, I'm trying to disable buttons in a view. I have this simple code and it works but it just doesn't disable the buttons which I am telling it to do.
class Confirmation(discord.ui.View):
@discord.ui.button(label='Accept', style=discord.ButtonStyle.success)
async def accept(self, interaction_: discord.Interaction, button):
if interaction_.user.id != enemyplayer.id:
await interaction_.response.send_message('This is not for you.')
return
nonlocal accepted
nonlocal buttonPressed
accepted = True
buttonPressed = True
self.accept.disabled = True
self.decline.disabled = True
await interaction_.response.defer()
@discord.ui.button(label='Decline', style=discord.ButtonStyle.red)
async def decline(self, interaction_: discord.Interaction, button):
if interaction_.user.id != enemyplayer.id:
await interaction_.response.send_message('This is not for you.')
return
nonlocal buttonPressed
buttonPressed = True
self.accept.disabled = True
self.decline.disabled = True
await interaction_.response.defer()
view = hunt()
await ctx.send(embed=random.choice(lis23),view=hunt())
``` embed and the view is not sent
You need to edit the message with the updated view
oh ok
like await (await interaction.original_message()).edit(view=self)?
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
Any help?
No error btw
Hey pplz, I’m having a slight problem with my bot, if someone can help. I can’t provide the code right now but I figured to ask to narrow it down.
I have a large @tasks.loop and every time it competes, the bot shuts down and restarts. There’s no error, it just restarts. Does anyone know what the issue might if they had it before? Will post the code later when I can
some blocking code in the loop possibly
what is hunt?
A command
well, you can't send a command in view
you can only send an instance of discord.ui.View
Oh btw
How can I make the button disabled for the user who clicked it
only for the user who clicked it
Other users can still interact with it
I don't think discord's api supports that
you can send a message to the person to not click it, but you can't disable it for them and not for others
how can i fix this?
bg1.save(f"Temp_{user.id}.png")
await ctx.send(file=discord.File(f"Temp_{user.id}.png"))
os.remove(f"Temp_{user.id}.png")
and the error is:
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
Fun part...image is getting saved after the ctx part executes I guess which raises an error like above
Like I can see after the error rises, the image appears on the drive
It's doing again and again and my bot starts slow
How to fix it?
Deal with it :P
Or just buy a VPS, whichever works
you cant change it
avatar.url
what library?
you need to respond to interactions within 3 seconds, unless you defer it
using discord.py
how can I defer it?
Refer or defer?
Interaction.response.defer() it was iirc
!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...
yes
how do I implement it?
It's not gave the commands in cogs
interaction.response.defer()
it does.
yes you may approach the bench
Guys for discord.py 2.0 can you use txt file for storing
storing what? i'm getting worried 😳
Anything , data
it didn't work
Like anything , for example storing a prize name then loading it
.txt is not great for storing data, depending on the size you might want to use a .json or a database
txt files arent meant to store data that isnt static
That's not exclusive to d.py
You can
how can i fix this?
im pretty sure that happens because you havent loaded your cogs, hence why the commands arent registered
Oh
Ye dpy I’m talking about tho
Means after loading cogs?
check it out after you loaded them yes
Thanks
Dude you can always use txt files, you don't even need dpy to use them
it's not like d.py is the one providing file I/O support
i wonder why people use txt and json files as dbs over sqlite😔
isnt that dumb how you are loading the cogs later and expecting the commands to get added first
what does that method do?
why are you guys so aggressive dayum😭 
feisty today 
!d discord.Asset
ease of use
Ik but can I use it for dpy tho
sqlites only challage is learning sql lmao
yes you can, yes you can
yes, ofc should you? no.
Hi, I'm going to make a self role system using buttons. But I'm not sure how to start. This is gonna be a public bot, so I need some sort of command to create them, but I don't know how to generate buttons from the data.
Yeah and thats a lot more annoying that printing a line to a text file
For small amounts of data text files are fine
dpy does NOT remove the ability to read/write files
set the image size
you can Member.avatar.with_size(new size here) in 2.0
aightt
!d discord.Asset.with_size
with_size(size, /)```
Returns a new asset with the specified size.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
thanks !
Because as soon as you close the program all of that data gets lost
but its small data👀
they want persistent small data
Json is best for that tbh
what kind of data are you storing?
use a discord message as a database then
send a message with newline for each data 
200iq
Hey nice idea bro
...
json data can be converted to a dict which is better than having stringafied data
fetch the message, and read its content each time
thats like the best stuff i have heard since morning
asher: Hold my dump channel
lmao
i use a category as a table and text channels as columns and messages as rows🧍
hack into Discord and store your data into their database
😈
Sql inject into your program to build the database
that would be funny if discord doesnt have sanitary inputs
plot twist: discord uses mongo
The cost of the security will mean there will be some weak spots somewhere. 😄
better over getting your tables dropped
if all my tables drop my team will drop me 😨
are the teams out?
no

I havent got on to discord with sql yet, will have to look at picking up soon lol
DROP DATABASE yes
like using sql with a bot or using sql to execute code and connecting to the api and gateway with an sql based client🧍
they would have been fked up (no wait they already are) if they used that
they use scylla a nosql db
bot sorry, hahaha just randomly coming into a conversation half way lol
lollll
what was that random 🧍 for


