#discord-bots

1 messages · Page 1148 of 1

sleek gyro
#

so, how would i do this? where do i use the created_at output?

slate swan
#

created_at is a datetime.datetime object.

#

you'll be using .astimezone on it for your timezone

upper belfry
#
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'
upper belfry
fading marlin
#

what does your directory look like?

#

also, it's @client.command(), not client.command()

upper belfry
#

rip

sleek gyro
#

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)
sick birch
#

You can.. but it's not ideal

#

Having to loop through each channel and fetching

slate swan
# upper belfry

To me looks like you either need to change it to ./sea-soft-bot/cogs or move cogs up a level.

fallow mauve
#

in a message.listen event, does message.channel_id not work?

sick birch
#

It should

brave flint
#

Without getting current loop?

harsh harness
#

whenever i run my code it runs discord.py 1.7.3 even though i've installed 2.0, can anyone help please?

slate swan
#

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 🙂
sick birch
harsh harness
sick birch
vital glacier
#

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

slate swan
#

hello i want to ask if its possible to add buttons on published annoucements messages on the server following the channel.

slate swan
vital glacier
#

Wow, tell me something i dont know

slate swan
#

i dont think i know it

#

good experience here

slate swan
sick birch
#

Buttons are more suited for this

slate swan
#

It is, but your idea does sound better.

sick birch
#

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

slate swan
#

Oh, i wouldn't know how to rectify that bit, I have been trying for a few days since someone told me ^^

sick birch
#

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?

rain olive
#

💀

slate swan
#

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 🙂

sick birch
#

Yes, okay. The biggest problem here is the check.. it's quite flawed

harsh harness
sick birch
#

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

devout iris
#

How can i make competing status?

slate swan
slate swan
unkempt canyonBOT
slate swan
#

@devout iris for more info check the most recent pin which is mine pithink

sick birch
vital glacier
unkempt canyonBOT
#
Install packages with `python -m pip`

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.

vital glacier
#

oh so using pythin -m pip install would b better?

devout iris
slate swan
brave flint
devout iris
#

ahhh yess tysm

slate swan
#

👍

devout iris
#

:/

slate swan
#

ik yall dont help with music yt but is there a way for spotify i seen it on their page

hoary cargo
slate swan
# devout iris

look at the most recent pin of the channel it has a gist which has an example

slate swan
slate swan
#

i think spotify doesnt like when bots stream music from their platform

hoary cargo
slate swan
#

just follow the rulespWut

devout iris
#

what are differences between them?

#

also can i make mobile status?

hazy oxide
#

Invisible is unknown

#

Offline is offline

devout iris
hoary cargo
slate swan
slate swan
#

invisible is when youre online but you want to appear offline, the different is one is intentional

devout iris
slate swan
#

offline is for members iirc

devout iris
#

ah alrighty

slate swan
#

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

devout iris
#
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?

slate swan
#

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*

devout iris
#

i wasn't coding since a few months ago, a lot of things changed i guess

slate swan
devout iris
#

my old codes are not good working ehehe

slate swan
#

does anyone know?

devout iris
#

ooops fixed, activity ==> Activity

slate swan
#

yup activity lower case is a file

#

Which the Activity class is inside of

#

how does it now not work?

#

so confused

slate swan
devout iris
#

could you send slash commands docs?

quaint epoch
#

👉 👈 any discord wrapper based around threading

slate swan
#

does anyone know abt the problem im having like i have 0 clue how to fix

austere vale
#
  @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?

quaint epoch
austere vale
#

ohh i see

#

then how would i do that image and description if possible?

slate swan
#

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

deep mirage
#

we cant really help if your problem is 'it doenst work'

pulsar arch
#

anyone know how to use a webhook bot to send messages via python?

slate swan
deep mirage
#

show the code

slate swan
#

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)

deep mirage
#

paste there click save copy link

slate swan
#

you want me to paste 1000 lines of code?

deep mirage
#

I mean I dont know how to help you otherwise

slate swan
#

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)

deep mirage
#

might not wanna share your token but aight

slate swan
#

imma reset

deep mirage
#

oh lmao u said in vid aswell

slate swan
#

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

deep mirage
#

can you paste the code so I can read it through

slate swan
#

yea ill send it rq

#

ah now i keep getting event loop is closed

#

oh

inland torrent
#

oml i hate formatting while typing i keep accidentally clicking enter

slate swan
#

wait no thats cuz i reset my token. 💀

#

alr imma run it

#

weird imma send code

inland torrent
#

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

slate swan
#

there ya go @deep mirage

deep mirage
slate swan
#

none!

#

nothing works

#

tried like all commands no errors nothing just simply doesnt work

pulsar arch
#

anyone know how to use a webhook bot to send messages via python?

deep mirage
#

maybe it doens thave permissions to speak or doesnt have the right intents enabled

slate swan
#

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

slate swan
#

havent had this before trying to make a new bot

slate swan
#

@deep mirage i invited it to my server it has admin etc the permissions just still not working?

fading marlin
#

any errors? what dpy version are you using?

slate swan
#

nope!

#

this is on too just wont send messages

slate swan
fading marlin
#

print out discord.__version__

slate swan
#

alr

fading marlin
#

in your code

slate swan
#

btw idk if you seen but at 4:19pm it was working i came back an hour later from the store then it didnt

fading marlin
#
print(discord.__version__)
slate swan
fading marlin
#

do you have message content intents enabled?

slate swan
fading marlin
#

in your code too?

slate swan
#

well i should since it worekd an hour earlier because i didnt remove anything when i was at the store

fading marlin
#

could you check?

slate swan
#

what am i looking for here

#

content intents?

fading marlin
#

either discord.Intents.all() or ```py
intents = discord.Intents.default()
intents.message_content = True

or any other variation of ti
slate swan
#

i do not

fading marlin
#

then that's probably why your bot isn't working

slate swan
fading marlin
#

yes, and you pass in intents to the corresponding kwarg in your bot constructor

slate swan
#

alr i put tht in

#

tried my commands again not getting nothin

fading marlin
#

make sure you've passed the intents to the intents kwarg in your bot constructor too

slate swan
#

how do i do that?

fading marlin
#
bot = commands.Bot(..., intents=intents)
#

!intents perhaps this might help you too

unkempt canyonBOT
#

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.

slate swan
#

idk if that matters

fading marlin
#

nope, doesn't matter

slate swan
#

alright

fading marlin
#

although you should generally name your bot instances bot instead of client to prevent confusion

slate swan
#

yeah i know

fading marlin
#

no, don't instantiate 2 different bot classes

slate swan
#

yea i thought so. should i just put intents=intent right after the case_insensitive=True, part

fading marlin
#

sure

slate swan
#

alright

#

and how would i fix this?

fading marlin
#

you're using intents before defining it

slate swan
#

ah im dumb i had it below it

#

there we go

fading marlin
#

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

slate swan
#

yoo it works thanks Lee! your the guy

fading marlin
#

glad to help :)

stiff fern
#

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

fading marlin
#

that's a discord issue?

stiff fern
#

oh alright

balmy bobcat
#

hi, how do I use get_message?

#

send code

slate swan
#

also this

#

nvm on that

#

anyone know about this tho

visual island
slate swan
#

Whats the best library to use?

visual island
slate swan
shrewd apex
slate swan
#

Tysm

vital glacier
#

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

full valley
#

question, will trying to add a role to a member if they already have that role raise an error

#

just or pass it naturally

sick birch
#

There shouldn’t be an error

#

Though I would check the docs just to be sure

full valley
#

👍

ivory owl
#

is it possible that I can make my bot respond to both prefixed commands and slash commands?

visual island
#

!d discord.ext.commands.hybrid_command

unkempt canyonBOT
#

@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.
warm tulip
#

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:")```
hazy oxide
#

What is that atomic for?

slate swan
hazy oxide
#

Ya

slate swan
#

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

ivory owl
#

how do I take my bot offline from heroku?

hazy oxide
#

Turn off the host

ivory owl
#

where

#

there is something called maintenance mode. but turning it on doesn't do anything

hazy oxide
#

I forgot on which option

#

On resources

shrewd apex
ivory owl
#

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

paper sluice
#

you need to pass in intents

intents = discord.Intents.default() # choose the one you want
bot = commands.Bot(..., intents=intents)
ivory owl
#

oh okay

ivory owl
paper sluice
#

yes

slate swan
#

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

full valley
#

like many members or

ivory owl
#

does anyone have an example of a bot created with hybrid commands?

slate swan
slate swan
#

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

full valley
#

okimii, you got experience with pymongo by any chance?

slate swan
slate swan
slate swan
slate swan
#

by that i mean like is it just a file on my computer or do i need to have a website for it

slate swan
slate swan
#

!pypi aiosqlite

unkempt canyonBOT
slate swan
#

is mongodb any better?

full valley
#

no

#

go with sql :)

slate swan
#

sql is better imo

full valley
#

im using mongo rn for a project and not enjoying it

slate swan
#

sql's syntax quite basic and can be used with many languages and most companies use sql based dbs like postgresql

#

sqlbolt is where i learned sql, its quite a good course

placid skiff
#

was it possible to get one of the command parameter in a custom checks?

slate swan
placid skiff
#

yeah

slate swan
#

!d inspect.getargspec

unkempt canyonBOT
#

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.
slate swan
#

not sure if theres a better way tho

placid skiff
#

so it should be smth like:

def custom_check():
  def predicate(ctx):
    inspect.getargspec(predicate)
slate swan
#

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

placid skiff
#

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)
slate swan
#

commands.check just checks what the inner functions boolean value returns and then probably sets the check internally, not sure on how its done

vocal snow
unkempt canyonBOT
slate swan
#

interesting attrpithink

placid skiff
#
    raise TypeError(f"Cannot instantiate {self!r}")
TypeError: Cannot instantiate typing.Any
``` but wtf does this mean ![D_D](https://cdn.discordapp.com/emojis/960909884285648916.webp?size=128 "D_D")
#

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 D_D

vocal snow
#

You want Union[Context, ApplicationCommandInteraction]

slate swan
#

did he just try to initiate Any???😭

vocal snow
#

instantiate

slate swan
#

whats the difference?

placid skiff
#

Lmao don't ask me why but the fun fact is that it worked yesterday

vocal snow
#

iniating => starting something, instantiating -> creating an instance of something

slate swan
placid skiff
slate swan
vocal snow
#

no

#

what does iniating an object even mean !!!

paper sluice
#

parenthesising 😳

vocal snow
#

okimii im the indian here ur supposed to be good at english

slate swan
#

english isnt my main language bro

#

dont blame me🧍

vocal snow
#

🥸

placid skiff
vocal snow
#
- Red: 0xED4245
- Green: 0x57f287
- Blurple: 0x5865F2
swift pumice
#

hi zeffo

vocal snow
#

👋

shrewd apex
slate swan
#

allot of regulars are indian here, hun bun, sarth boo, zeffo and other very knowledgeable people

vocal snow
#

nova

slate swan
#

who

vocal snow
#

oh wait nova got banned

slate swan
vocal snow
#

how tf u forgot nova

slate swan
#

im joking

#

i have him added

robust fulcrum
#

@slate swan

slate swan
#

yeah

robust fulcrum
#

I confused how should I do time thing

#

Can you help pls

slate swan
#

!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)

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

0:00:05.045057
slate swan
#

the code won't work if you just copy paste it so make your own.

robust fulcrum
#

Thanks i just need to know starategy

shrewd apex
#

the Indian one not the knowledgeable one 😂

robust fulcrum
slate swan
#

wtf 1 minute

robust fulcrum
#

I tried times.replace(microsecond=0)

#

But i got error

slate swan
#

!d datetime.timedelta.total_seconds

unkempt canyonBOT
#

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.
slate swan
#

this gives you only seconds

#

convert it to minutes or anything you want

robust fulcrum
#

Ok

robust fulcrum
# slate swan !d datetime.timedelta.total_seconds
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

slate swan
#

noice, you didnt need asyncio for this btw

slate swan
slate swan
#

lucky, i wish i lived with hun bun or sarth boo😔

#

hun bun

#

Nice nick

#

ikr

shrewd apex
#

hunter is gonna be mad well not like he is online anyway

dusky pine
#

everyone is indian aaaaaaaaaaaa

#

am I indian

slate swan
#

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?

vocal snow
#

nvm Client doesn't have it

slate swan
#

rip

vocal snow
# slate swan rip

instead of manually parsing commands like this I would recommend using the commands ext instead

slate swan
#

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
fallow girder
#

how do i do i have this problem?

slate swan
#

!rule 7

hazy oxide
slate swan
#

Hiii zeffo GuraHeart

fallow girder
hazy oxide
#

np

wanton cipher
#

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?

vocal snow
#

!d discord.ui.View

unkempt canyonBOT
#

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.
vocal snow
#

set the timeout to None

slate swan
vocal snow
#

so much effort ashley 🙏

slate swan
#

and you still ignore my greetings, fml AScry

wanton cipher
#

OH, it's the view, ight, thank you @slate swan and @vocal snow :)

fallow girder
royal oar
#

Quick yes or no.
Can Cog names have aliases?
If not is there anyway for the help command to use different languages for it?

hazy oxide
fallow girder
vocal snow
royal oar
#

like say the catergory

#

where commands are stored

#

like:

vocal snow
#

Why would you need that?

royal oar
#

Im making my bot Bilingual

#

multiple languages

vocal snow
#

Yes, but where would the cog aliases be used?

#

Are you going to access them in a custom help command?

royal oar
#
!help <catergory>
#

And yes

dusky pine
slate swan
vocal snow
# royal oar And yes

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

royal oar
#

Hmm mk then, thank you

slate swan
#
        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
shrewd apex
#

i got goosebumps saying that

slate swan
shrewd apex
#

0-0

#

ic

wanton cipher
#

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

slate swan
#

where interaction is an instance of Interaction

slate swan
wanton cipher
#

damn, ight thanks

wanton cipher
paper sluice
wanton cipher
#
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)
hardy yoke
# wanton cipher ```py class VoteView(disnake.ui.View): def __init__(self, message: disnake.M...
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
wanton cipher
#

and funny enough, just wrote something like that

slate swan
#

view.message = ...

wanton cipher
#

...

#

oh

slate swan
#

that's how it's getting the message what

#

since send returns a Message obj

wanton cipher
#

oh yeah

#

OH

#

I didn't notice the bottom

paper sluice
shell wing
#

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
dusky pine
#

I'd assume it's probably one of those "fonts"

shell wing
#

oh alr

#

no other way to add them ?

vestal mist
quartz reef
#

regarding music bots, what's exactly the autoplay mode? It tells the bot to fetch tracks from some history after the queue is empty?

vocal snow
slate swan
#

What’s the most accurate way to find a user’s account creation date/time down to the millisecond

vocal snow
#

!d discord.User.created_at

unkempt canyonBOT
#

property created_at```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
vocal snow
#

That's what the api gives, so it should be the most accurate

robust fulcrum
slate swan
#

nice

robust fulcrum
dawn shard
#

try ctx.message.add_reaction

slate swan
#

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

visual island
#

You miss typed comma as underscore

#

in on_reaction_add function parameter

robust fulcrum
#

@slate swan how to fix this?

livid hedge
#

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"

slate swan
#

what you trying to do

visual island
livid hedge
#

Do I have to use Rapptz version?

slate swan
#

You literally asked 2 minutes ago. discord.py is the go to, but find what you prefer, not what people say.

slate swan
slate swan
slate swan
livid hedge
#

perfect

robust fulcrum
slate swan
#

show code..

robust fulcrum
# slate swan 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

visual island
robust fulcrum
#

Ok

slate swan
#

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

gusty shard
#

can i create a embed without title and desc?

#

just fields

placid skiff
#

Nope, but you can use an invisible character to do that

visual island
placid skiff
#

oh nvm i misunderstood the question lmao

robust fulcrum
slate swan
#
async def command(ctx,*, argument):
  ...
robust fulcrum
#

Ok

#

Ty

robust fulcrum
placid skiff
#

lmao word similarity and machine learning

robust fulcrum
unkempt canyonBOT
slate swan
#

difflib may work too

visual island
#

difflib works quite well yeah

robust fulcrum
visual island
#

it's not hard

robust fulcrum
#

Its hard 🔥

visual island
#

just combine every command name and aliases and then compare the input with difflib.get_close_matches()

robust fulcrum
slate swan
#

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

unkempt canyonBOT
slate swan
#

note that ctx.command would be None here

robust fulcrum
visual island
#

use it like a normal attribute

robust fulcrum
#

Any short example please?

visual island
#
@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?
robust fulcrum
#

@visual island

#

Can I ask

#

How can I get list of all comand of my bot?

slate swan
#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
sour basalt
#

activity = discord.Activity(type=discord.ActicityType.watching, name="TelSpin")
AttributeError: module 'discord' has no attribute 'ActicityType'

slate swan
sour basalt
#

Ohhh thk

#

@commands.dynamic_cooldown(bucket, retry_after, self._buchets.type)
AttributeError: module 'discord.ext.commands' has no attribute 'dynamic_cooldown'

placid skiff
#

D_D it is just cooldown

slate swan
#

you're not using 2.0

slate swan
unkempt canyonBOT
#

@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.
placid skiff
#

oh they add a dynamic_cooldown deco? LMAO

#

I'm really glad that disnake exists

slate swan
#

yes, it can be used when you want to return a different cooldown for different bucket

#

!d disnake.ext.commands.dynamic_cooldown

unkempt canyonBOT
#

@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.
slate swan
#

exists in disnake too, while it was forked

placid skiff
#

They added it in version 2.0, so a lot before d.py 2.0 release lmao

slate swan
#

it has always been in dpy 2.0...

placid skiff
sour basalt
#

uhm i dont understand what i should do lol

placid skiff
#

this:
pip install git+https://github.com/Rapptz/discord.py

#

in your console

shell wing
#

can i do

sdad \n \n sada
``` ??
#

for like 2 line breaks

placid skiff
#

yup

shell wing
#

alr cool

devout iris
#

How can i make add to server button?

slate swan
devout iris
#

Oh ty

pseudo crystal
#

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

slate swan
#

"doesnt work" doesnt' explain anything.

pseudo crystal
#

okey i ficed it

#

fixed*

#

it was bc avatar.url

shell wing
#

how can i make a channel edit loop
like it edits the channel name every 1hr or so

shell wing
#

bot = Bot() do i have to declare this everytime i end a class ?

shrewd apex
#

how to add text to modal like an embed description

paper sluice
shell wing
#

and can i like make smh like this

class ....
class ...

now the commands using both the class
shrewd apex
#

cogs?

paper sluice
shell wing
shrewd apex
paper sluice
#

!d discord.ui.Modal

unkempt canyonBOT
#

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...
shrewd apex
#

linter shows no such attribute either

#

i tried in the label for textinput but there seems to be a size limit

paper sluice
#

oh, ok hold on

shrewd apex
#

sure np

paper sluice
#

can you even add text to modals lol

shrewd apex
#

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🤣

paper sluice
#

text input seems like the only way to add stuff to modals

shell wing
#

v2 cogs example ?

pseudo crystal
#

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

paper sluice
# shell wing v2 cogs example ?
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))
shrewd apex
#

i entered the text i wanted to display in a textinput field

#

now i need a way to stop user from typing there preferably

slate swan
#

Umean placeholders?

#

sry gtg

shrewd apex
#

placeholders don't give me enough character limit either

slate swan
#

Gn all

shrewd apex
#

gn

shell wing
paper sluice
shell wing
#

thanks

shell wing
#

like it says

paper sluice
#

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

shell wing
paper sluice
#

do os.listdir('cogs') then remove the .py from the name of the cogs before loading

shell wing
#

so i made the cog outside the folder i.e. in the same directory with the main.py
and this
it wont load...

slate swan
#

dont you think that it will overwrite the setup_hook only when the function is ran

pseudo crystal
#

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}})```
gusty shard
#

list = ['🍉', '🍋', '🍒', '🍇', '🔔', '🍎', '🪐']

how can i get a random element from that list?

unkempt canyonBOT
#

7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.

slate swan
#

just check with if final[0] == final[1] and final[0] == final[2]

gusty shard
#

so..

#

also i already found the answer, thanks

slate swan
pseudo crystal
#

hehegigachad

zinc plinth
#

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?

dull terrace
#

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

torn sail
dull terrace
#

depresso

sour basalt
#

Preparing wheel metadata ... error

sick birch
#

Hard to keep any player retention for long with any game, really

slate swan
dull terrace
#

assuming one play session a day i've got like 0.4% doge_kek

velvet compass
#

A KeyError would mean that a key is not present in a dictionary

sour basalt
#

Preparing wheel metadata ... error ERROR: Command errored out with exit status 1:

dull terrace
#

are you sure the key is a string?

sour basalt
#

inbstalling discord 2.0

velvet compass
#

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]

slate swan
#

brad NM_PeepoBlushHat

velvet compass
#

Alrighty, thats a different user id

#

So '941750986551205930' is not present

dull terrace
velvet compass
#

Either add it, or handle when a key is missing

slate swan
#

am I just invisible or everybody ignores me on purpose here

slate swan
#

show code

velvet compass
#

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

slate swan
velvet compass
#
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

slate swan
#

you could you just use get?

velvet compass
#

Since its a json object its a bit harder to try and add to it if there is no user already present

velvet compass
#

But I'm not a good programmer

slate swan
#

imagine capping

velvet compass
#

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

sick birch
velvet compass
#

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?

sick birch
#

Which follows a relatively simple pattern:

  1. load the contents of your JSON file into an in-memory python dictionary
with open("filename.json", "r") as f:
  data = json.load(f)
  1. Make any changes
data[...] = ...
data[...] = ...
data[...] = ...
  1. Save the dict back into the JSON file:
with open("filename.json", "w") as f:
  json.dump(f, data, indents=4)
sour basalt
#

how fix this i trying instasll discord py 2.0

sick birch
#

You asked how to read/write into a JSON file?

slate swan
#

this command is too error-prone with KeyError exceptions

sick birch
velvet compass
#

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
sick birch
#

Another way:

if user_data.get(str(userr.id)):
  # it exists
else:
  # it doesn't
velvet compass
#

Thats the better way ^

sick birch
#

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?

slate swan
#

i'd suggest migrating to some sql based database like sqlite3 instead.

sick birch
#

Even better if you can throw an ORM in 😄

glad cradle
#

to make the code less redundant

lone dust
slate swan
#

How to add and remove emojies in a server with discordpy?

#

!d discord.Guild.delete_emoji

unkempt canyonBOT
#

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.
slate swan
#

hey oki

#

are you not participating?😔

slate swan
slate swan
raven bolt
slate swan
slate swan
#

because it can store data doesnt mean its a db but people do it 😔

slate swan
slate swan
#

its a college entrance exam so i can't miss it

#

forget college

#

😼

#

how about forget you

#

not nicelemon_sentimental

#

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

slate swan
slate swan
slate swan
#

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 meshipit

#

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 whateverducky_dave

winter gull
#

What are the common ways to make our bot efficient and faster?

slate swan
#

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^
austere vale
#
  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?

sour basalt
#

?

winter gull
#

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> ?

slate swan
#

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

unkempt canyonBOT
#

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").
winter gull
#

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

slate swan
winter gull
slate swan
winter gull
#

it does?

slate swan
#

yes the master branch

#

it's usable and available to install

winter gull
slate swan
#

i mean do you commit in the code?

winter gull
#

oh i have written most of my code in pycord now

winter gull
slate swan
#

nope, after writing data

winter gull
#

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

slate swan
#

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

winter gull
#

alright, thankyou!!

sour basalt
#

` Preparing metadata (pyproject.toml) ... error
error: subprocess-exited-with-error

× Preparing metadata (pyproject.toml) did not run successfully.
│ exit code: 1
`

winter gull
#

How can I call a function whenever i stop the code or turn off the bot?

slate swan
#

place it after bot.run()

#

it will get executed when you close the bot using ctrl+c in your terminal

winter gull
#

oh alrightt

slate swan
#

if you're using replit just create another repl

#

if you're on a debian based distro ```bash
$sudo apt install libffi-dev

sour basalt
#

YeA i download

#

now

slate swan
#

now do the pip install cmd again

sour basalt
#

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
`

slate swan
#

do basic checks, update python and pip

#

and use python -m pip if you're using pip

golden tapir
#

how can i kick someone if they say something

#

just an example say that said "." then they should get kicked

slate swan
#

!d discord.on_message

unkempt canyonBOT
#

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.
slate swan
#

check for . in message.content

#

you can use message.author to get the member and kick it

golden tapir
#

thank u

golden tapir
#

how can i tell when someone joins

#

my server

sick birch
#

Looks like for some reason interaction.guild is None, maybe because it's not cached?

flint widget
#

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)
slate swan
#

im pretty sure message_content isnt a thing in disnake

#

!d disnake.Intents.message_content

unkempt canyonBOT
flint widget
#

Hmm it seemed to work when I just enabled it now 🤔

slate swan
#

seems like it is implemented

flint widget
#

ah

#

Yeah I've not used it in ages so just trying to get to grips with it

slate swan
#

same

flint widget
#

The documentation on setting it up isn't great but maybe it's just been added in

slate swan
#

yeah you would need to go through a class's attribute etc

robust fulcrum
slate swan
#

yes

robust fulcrum
slate swan
#

typing.Set[commands.Command]

#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
slate swan
robust fulcrum
slate swan
#
    cursor.execute(f"SELECT user_id FROM eco WHERE user_id = {author.id}")
NameError: name 'author' is not defined```
#

confused

robust fulcrum
slate swan
#

OH ok thanks

robust fulcrum
#

Try once

slate swan
#

ok i have a new one

#
    if message.author.client:
AttributeError: 'Member' object has no attribute 'client'```
dusky pine
#

do you know your datatypes, bro?

#

!d set

unkempt canyonBOT
#
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'])`...
robust fulcrum
#

Can you help

#

Replit is always adding humanize package again and again even i have installed and my bot is starts slow

smoky cedar
#

How would I add discord py 2.0 to a requirements file?

dusky pine
slate swan
smoky cedar
#

when is 2.0 gonna officially release for d.py lol

slate swan
slate swan
worthy mortar
#

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?

shrewd apex
#

poetry add requests

worthy mortar
#

it seems to be only be an issue withimport requests too
importing json and other libraries is fine

slate swan
#

the line asher told is a shell command you need to do in the terminal

#

not in your py file.

worthy mortar
slate swan
#

what's the exact error

rain olive
worthy mortar
#

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

slate swan
#

Totally a replit issue.

elfin moon
#

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()
slate swan
#
  view = hunt()

  await ctx.send(embed=random.choice(lis23),view=hunt())
``` embed and the view is not sent
torn sail
elfin moon
#

like await (await interaction.original_message()).edit(view=self)?

elfin moon
#

i did

#

it works

#

Thanks thx

torn sail
#

I think user.icon would be None but lemme check

#

*user.avatar

#

!d discord.User.avatar

unkempt canyonBOT
#

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").
alpine pewter
#

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

vocal snow
paper sluice
slate swan
paper sluice
#

well, you can't send a command in view

#

you can only send an instance of discord.ui.View

slate swan
#

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

paper sluice
#

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

slate swan
#

how can i fix this?

sturdy barn
#
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

robust fulcrum
dusky pine
#

Or just buy a VPS, whichever works

robust fulcrum
#

It's annoying

slate swan
#

you cant change it

robust fulcrum
#

Replit ded today

#

It's not opening

slate swan
#

or just try to poetry add

hazy oxide
slate swan
#

you need to respond to interactions within 3 seconds, unless you defer it

sturdy barn
robust fulcrum
#

Refer or defer?

slate swan
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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...
slate swan
#

yes

sturdy barn
#

how do I implement it?

robust fulcrum
slate swan
slate swan
robust fulcrum
#

I have proof

dusky pine
warped mirage
#

Guys for discord.py 2.0 can you use txt file for storing

dusky pine
warped mirage
dusky pine
#

user data?

#

like coins, stats, etc?

slate swan
warped mirage
#

Like anything , for example storing a prize name then loading it

paper sluice
robust fulcrum
slate swan
#

txt files arent meant to store data that isnt static

dusky pine
#

You can

slate swan
#

how can i fix this?

slate swan
# robust fulcrum

im pretty sure that happens because you havent loaded your cogs, hence why the commands arent registered

warped mirage
robust fulcrum
#

Means after loading cogs?

slate swan
#

check it out after you loaded them yes

robust fulcrum
#

Thanks

dusky pine
#

it's not like d.py is the one providing file I/O support

slate swan
#

i wonder why people use txt and json files as dbs over sqlite😔

slate swan
# robust fulcrum

isnt that dumb how you are loading the cogs later and expecting the commands to get added first

slate swan
#

why are you guys so aggressive dayum😭 yert

#

feisty today pithink

#

!d discord.Asset

warped mirage
slate swan
dusky pine
slate swan
#

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.

slate swan
#

For small amounts of data text files are fine

dusky pine
#

dpy does NOT remove the ability to read/write files

slate swan
#

well if youre going to store small amounts of data why not have variables?

#

^

slate swan
slate swan
#

aightt

#

!d discord.Asset.with_size

unkempt canyonBOT
#

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`.
slate swan
#

thanks !

slate swan
slate swan
dusky pine
#

they want persistent small data

slate swan
#

Json is best for that tbh

dusky pine
#

what kind of data are you storing?

slate swan
#

use a discord message as a database then

#

send a message with newline for each data loooli

#

200iq

dusky pine
shrewd apex
#

...

slate swan
#

json data can be converted to a dict which is better than having stringafied data

#

fetch the message, and read its content each time

dusky pine
#

Just hope swas.py or Lucas doesn't see this

shrewd apex
#

thats like the best stuff i have heard since morning

slate swan
#

asher: Hold my dump channel

shrewd apex
#

lmao

slate swan
#

Put all of your code into registry keys

#

Then read it at runtime

slate swan
dusky pine
#

hack into Discord and store your data into their database

slate swan
#

imagine you can use sql injection

#

🥴

dusky pine
#

😈

slate swan
#

Sql inject into your program to build the database

#

that would be funny if discord doesnt have sanitary inputs

dusky pine
#

plot twist: discord uses mongo

slate swan
#

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 😨

shrewd apex
#

are the teams out?

slate swan
#

no

#

I havent got on to discord with sql yet, will have to look at picking up soon lol

dusky pine
#

DROP DATABASE yes

slate swan
slate swan
#

bot sorry, hahaha just randomly coming into a conversation half way lol

#

lollll