#discord-bots

1 messages Β· Page 229 of 1

magic whale
#

it is working now

#

it was not working before and now suddenly it is working

hushed galleon
#

btw did you actually use that command i described or just pip install discord.py? the former is for installing the development version which isnt recommended

magic whale
#

the one u said to use.

hushed galleon
#

i was talking about the pip install command, but that line looks correct

slate swan
#

Inter process communication

magic whale
thin raft
thin raft
#

ty

slate swan
#

Ipc let's two processes communicate

#

So your site can request data from your bot

#

And vice versa

#

It's like an api

#

But way easier to use

hushed galleon
#

discord-ext-ipc is what i had once used, but the project died

#

now on my last exploration i just used the same event loop to host the webserver and bot

shrewd apex
#

i made a aiohttp application from scratch to add routes and stuff more like a mini fastapi by mini i mean really mini like one files mini loooli

thin raft
#

it was sadge updating to 2.x

#

and no longer suported :c

#

I also did once in two separated py instances but connected through a mysql

shrewd apex
#

bad idea

#

but works ig if writes are not too frequent

#

shouldnt be an issue

timid spade
#

exploring on github is so complicated

shrewd apex
#

where the exploration

thin raft
#

all it needed to do as it was a shitty project

timid spade
#

i have never used it like that

#

i have only clicked on links

shrewd apex
#

technically i dont really look at github either i just discover or click on interesting repos i may find when searching up on coding stuff

#

thats how u find hidden gems

shrewd apex
timid spade
#

i am trying to find it

shrewd apex
#

u can use the decorator

#

!d discord .ui.button

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

shrewd apex
#

wut

#

.

#

y the diffeerence

#

*discrimination

#

anyways any reason u wanna subclass in general?

timid spade
shrewd apex
#

its there in examples tho

#

like persistent views and other onces

timid spade
#

in buttons you only subclass the view class right?

shrewd apex
shrewd apex
timid spade
shrewd apex
#

whats the use case one way is as show in the link i gave u

#
view = discord.ui.View()
button = discord.ui.Button()
button.callback = some async function
view.add_item(button)

this is way too more of a monkey patch way tho

timid spade
#

i was trying something like this and i was only getting one button

shrewd apex
#

u cant stack

timid spade
#

i have to separate call back of each

shrewd apex
#

u want same?

#

also a decorator has different params

timid spade
shrewd apex
#

its async def callback(self, inter, button) iirc

#

check the order tho idr

shrewd apex
timid spade
timid spade
fading egret
#

discord.ext.commands.errors.ExtensionFailed: Extension 'market.itemFunctions' raised an error: TypeError: Command 'update' is a duplicate

what does this error mean?

shrewd apex
tall temple
#
    with open(f'users_data/{ctx.guild.id}.json', "a") as users_data :
        sdl = "\n"
        json.dump(dict, users_data)
        users_data.write(sdl)
        return await ctx.respond(embed = discord.Embed(title = f"", description = f"\βœ…  *・  Successfully saved your payment method infos as :*\n\n> **Name :** `{payment_method_name}`\n> \n> **Address / Link :** `{info}`\n> \n> **(Extra) Fee :** `{fee}`", color = 0x45b557))
        print(Fore.GREEN + "Successfully calculated for {ctx.author}")
        users_data.close()
#

pls help i don't know what's the problem here

magic whale
#

how do i check if the user has a specific permission or not?

#

anyone plz???

slate swan
slate swan
#

@commands.has_permissions(administrator=True)

magic whale
#
@code_bot.tree.command()
async def add_coins(interaction: discord.Interaction , user_id: str , coins: int):
    await interaction.response.send_message("You have admin permission.")

how do i check for this?

slate swan
#

u can change administrator to the permission u want it to have

#

@code_bot.tree.command() @commands.has_permissions(administrator=True) async def add_coins(interaction: discord.Interaction , user_id: str , coins: int): await interaction.response.send_message("You have admin permission.")

#

should work like this i think

magic whale
#

it is not working

slate swan
#

is a error coming?

tall temple
#

help pls guys

magic whale
tall temple
#

can you explain more ?

magic whale
#

not unless i have seen the code

magic whale
#

it is not giving an error but even when i don't have admin perm it is responding with that message

slate swan
#

oh yeah

#

you have to do an error thingy

#

`@code_bot.tree.command()
@commands.has_permissions(administrator=True)
async def add_coins(interaction: discord.Interaction , user_id: str , coins: int):
await interaction.response.send_message("You have admin permission.")

@add_coins.error
async def add_coins_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have permissions to use this command!")`

#

like this

magic whale
slate swan
#

bruh

#

@code_bot.tree.command() async def add_coins(ctx, user_id: str , coins: int): if ctx.author.guild_permissions.administrator: # Execute the command await ctx.send("You have admin perms") else: # Send an error message await ctx.send("You don't have permissions to use this command!")

#

i hope this works xD

magic whale
#

now it is giving error

#
Traceback (most recent call last):
  File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\JAPAN COMPUTERS\Desktop\Codestore Bot\zmain.py", line 104, in add_coins
    if ctx.author.guild_permissions.administrator:
       ^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\JAPAN COMPUTERS\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'add_coins' raised an exception: AttributeError: 'Interaction' object has no attribute 'author'
slate swan
#

oh im stupid

#

@code_bot.tree.command() async def add_coins(interaction, user_id: str , coins: int): if interaction.user.guild_permissions.administrator: # Execute the command await interaction.response.send_message("You have admin perms") else: # Send an error message await interaction.response.send_message("You don't have permissions to use this command!")

#

i used ctx instead of interaction

slate swan
#

Nice

magic whale
#

thanks alot

slate swan
#

no problem

tall temple
#

help pls,i don't know what's the problem :/

#
from discord.ext import commands
import discord
import time
from colorama import init
from colorama import Fore, Back, Style
import json

config = json.load(open("config.json", encoding="utf-8"))
init()
print(Fore.BLUE +   """
Discord : --link--
Instagram : @true_medra\n\n\n
                    """)
unborn zenith
#

can anyone help?

fading marlin
austere token
#

who can help me with discord bot

tender mantle
#

did Discord really fuck up the hyperlinks in the embed descriptions 😭

austere token
#

?

tall temple
#

oh my bad

tender mantle
#

like the format

fading marlin
#

^

tender mantle
#

search for a json format checker online, there's a bunch and they're really useful to see if you missed something

#

i use that

tall temple
naive briar
#

The content of the JSON file

austere token
#

i cant fix my stupid bot tho

#

[2023-04-18 03:32:02] [ERROR ] discord.client: Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\georg\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\georg\OneDrive\Desktop\BOTVERIFY6.py", line 45, in on_member_join
captcha_image = generate_captcha()
^^^^^^^^^^^^^^^^^^
File "C:\Users\georg\OneDrive\Desktop\BOTVERIFY6.py", line 28, in generate_captcha
image_data = image.generate(code)
^^^^^
NameError: name 'image' is not defined

remote crane
#

audio_state = participant.voice.audio
AttributeError: 'VoiceState' object has no attribute 'audio'```
naive briar
#

!e

uwu
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     uwu
004 | NameError: name 'uwu' is not defined
naive briar
#

The variable doesn't exist

blazing flint
#

Yeah it’s pretty obvious

#

I assume he got the code from somewhere else

austere token
#

yes

blazing flint
#

Send it to me

austere token
#

i changed 15 times things or anything but is not working

blazing flint
#

You are not defining an image variable

unborn zenith
#

i am trying to make a discord bot which translates the given content.
but i am getting a problem where its also translating the language code with the content itself. I will be really thankful if someone can help

blazing flint
unborn zenith
#

so basically i made a bot which translates the sentence its given

#

it does that with googletrans library

#

the syntax is this

#

!translate how are you ru

#

the !translate is to activate it

#

how are you is the sentence to translate

#

and ru is the language code

#

u with me?

smoky sinew
smoky sinew
#

yes what's your problem

unborn zenith
#

the bot is also translating the language code with the sentence

smoky sinew
#

just check if the last word is a valid language code with .split()

#

!e ```py
string = "how are you ru"
text = string.split()[:-1]
language_code = string.split()[-1:]

print(text)
print(language_code)

unkempt canyonBOT
#

@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | ['how', 'are', 'you']
002 | ['ru']
smoky sinew
#
if language_code.lower() in (
    "en",
    "es",
    "ru",
    "fr"
):
    translate(text, language_code)
else:
    print("error")
unborn zenith
austere token
#

github bot not works

#

chatgpt bot not works 😦

#

I cant make a simple bot to work

smoky sinew
austere token
#

nothing is working

#

only errors and errors and errors

#

idk how to even fix them even if i ask chatgpt he is fixing and and again another errors

sick birch
austere token
sick birch
#

It's bad for pretty much anything programming related

austere token
#

I got this

#

I want verify bot for new members to verify and after they got verified the bot should give them a role

unborn zenith
smoky sinew
#

my dms are closed if you read my bio

unborn zenith
#

ohh sorry

#

i thought i could send u the code and maybe u would implement the changes in that?

smoky sinew
#

i can't code your bot for you

unborn zenith
#

no

#

not the whole bot just the split thing

smoky sinew
#

i can't code it for you

unborn zenith
#

thats fine i will just do the changes and if it doesnt work i will ask u

#

is that alright?

smoky sinew
#

ok

unborn zenith
#

noice

unborn zenith
#

@smoky sinew uhh sorry to ping but its not working

unborn zenith
#

nvm i got it

#

tysm tho

smoky sinew
#

it's @commands.hybrid_command

#

also you can remove name="ping" and with_app_command=True because those are the defaults

#

then check if the cog is loaded

#

also make sure your bot tree is syned

north kiln
#

I think I have asked this before but is it not possible to sync a change to global slash command to one guild only

#

as syncing with guild specified only syncs the guild commands

hushed galleon
unkempt canyonBOT
#
Certainly not.

No documentation found for the requested symbol.

hushed galleon
#

oh right copy_global_to

#

!d discord.app_commands.CommandTree.copy_global_to

unkempt canyonBOT
#

copy_global_to(*, guild)```
Copies all global commands to the specified guild.

This method is mainly available for development purposes, as it allows you to copy your global commands over to a testing guild easily.

Note that this method will *override* pre-existing guild commands that would conflict.
north kiln
#

using that results in 2 copies of slash command in my server, I know it is because I synced a global command before but I couldn't find a workaround for it

hushed galleon
#

then your only choice is removing your global commands

north kiln
#

I am currently using another account for testing

#

maybe I should just do that

vague basin
north kiln
#

what does your command look like

#

!startgame <id1> <id2>?

smoky sinew
#

if you used a bot instead of a client you could do:

#
@bot.command(name="startgame")
async def start_game(ctx, members: commands.Greedy[discord.Member]):
    for member in members:
        print(member.name)
vale wing
#

Griddy

#

Why do the griddy when you can just *members

vocal snow
#

i think mudkip purposefully gives bad advice so that Leaf will be the best bot in the world

#

is true @smoky sinew ?

gray goblet
#

Anyone knows how to directly access discord API using https requests (or something similarly "low level"), not through a library like discord.py?
I can't find any tutorial for that.

vocal snow
gray goblet
#

I'm lost in the documentation πŸ˜΅β€πŸ’« Do you know any beginner friendly tutorial?

vague basin
vale wing
#

Most of API docs are similar

#
  1. Find how to authorise
  2. Use endpoint you need
young dagger
#

Is this normal behaviour? It's RESUMING almost every hour.

0|blitzcra | [2023-04-18 05:12:46] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 05:35:35] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 07:05:45] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 07:20:21] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 07:36:14] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 08:22:43] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 08:56:19] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.
0|blitzcra | [2023-04-18 09:28:45] [INFO    ] discord.gateway: Shard ID None has successfully RESUMED session 53cab6af2be7dc3d0bb1e6d3feccdffa.```
vocal snow
#

also are you familiar with http at all?

cloud dawn
young dagger
young dagger
cloud dawn
young dagger
#

Where can I add it to avoid this kind of stuff?

cloud dawn
#

That it will print that message? I mean it's a nice reminder that the bot is still online.

young dagger
cloud dawn
austere token
#

I cant make a faking bot to work

#

People already made this bot snd shared the code. Why i cant make them to work

cloud dawn
#

What is the issue?

austere token
young dagger
cloud dawn
#

Is this Hikari btw?

young dagger
#

What is Hikari? πŸ€”

gray goblet
vocal snow
cloud dawn
gray goblet
young dagger
young dagger
cloud dawn
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

young dagger
# cloud dawn !paste

I know. I just prefer to DM you the link to not post my code in public. But we can keep the conversation here, it's just for the link.

cloud dawn
#

oki

#

I still recommend changing the API key since there are people that like to guess paste urls.

cloud dawn
cloud dawn
#

As for the code if you wrote it yourself, very nicely written. Could be cleaned up a bit but other than that looks gut.

cinder horizon
#

cant set a gif pfp for my bot can i?

cloud dawn
cinder horizon
#

....back to da gloom.....thenks mayte

austere token
#

who can help me to setup a bot from github

vocal snow
slate swan
#

you need to learn some good amount of python first because discord.py (or other libs) are a rather complicated library to use

vale wing
slate swan
vale wing
vale wing
slate swan
# austere token no

If your not planning on making changes to the code, then all you need to do is

  1. set up an application in the discord developers portal
  2. read the docs on the github page to what permissions/intents its need, do NOT give it admin,
  3. Find a host for server (if you want it 24/7) otherwise, use a VM on your own machine if your not fussed about availability.
  4. copy the files into a directory on the server
    4 Addd the auth token from your discord app to the code and then you should be able to invite it your server with invite link in the discord portal.
young dagger
slate swan
young dagger
#

I have a another question. I'm currently using ReturnDocument from PyMongo, but I want to switch to using Motor instead. Is it possible to achieve the same functionality using Motor?

from pymongo import ReturnDocument

counter_doc = await counter_collection.find_one_and_update({"_id": "case_counter"}, {"$inc": {"count": 1}},
                                                                   return_document=ReturnDocument.AFTER)```
slate swan
magic whale
#

can anyone plz tell me how do i make a dropdown selection box?

#

like this

hushed galleon
#

if you specifically want to select (category) channels, use discord.ui.ChannelSelect instead

magic whale
hushed galleon
#

use the view= argument like you normally would when sending a message

magic whale
# hushed galleon use the view= argument like you normally would when sending a message
options = [
                dd.SelectOption(label='Option 1', description='This is option 1'),
                dd.SelectOption(label='Option 2', description='This is option 2'),
                dd.SelectOption(label='Option 3', description='This is option 3'),
                    ]
                my_dropdown = ddu.Select(placeholder='Select an option...' , options=options , custom_id='dropdown_menu')
                await interaction.edit_original_response(content=f"**Choose a category from the dropdown below! :smiling_imp:**" , view=my_dropdown)

is this correct?

hushed galleon
#

there's a difference between views and components like select menus

#

the view= parameter only takes a view, and views contain the components to be sent with your message

magic whale
#

then how do i do it?

hushed galleon
#

the other syntax is to subclass View and use the select decorator, which might be easier to understand since you only have to instantiate one class to pass to view=
https://github.com/Rapptz/discord.py/blob/master/examples/views/confirm.py py class MyView(discord.ui.View): @discord.ui.select(options=[...]) async def on_select(self, interaction, select): value = select.values[0] await interaction.response.send_message(f"You picked: {value}")

young dagger
# cloud dawn No.

It's weird because I'm not receiving these messages with my Modmail bot (which was not coded by me)

cloud dawn
quick gust
#

could any of you link me the discord markdown guide that was sent here before? I cant find it

#

found it

austere token
tall temple
#

pls how to make a slash command only usuable py server crown owner ?

austere token
#

why these bots from github are so hard to setup

#

no clue what im doing

slate swan
tall temple
#

thx

slate swan
austere token
#

idk whatys going on

slate swan
#

So what discord bot is it?

tall temple
#

what should i write ?

sick birch
austere token
#

what u mean'

slate swan
tall temple
slate swan
#

Oh server owner, that is how.

tall temple
slate swan
#

Yes it does check that. The server owner is an Administrator the only difference is, a normal admin can't remove the server owner or change server owner, etc. Unless I have completely missed something in the role heirarchy. I would highly recommend not giving admin to anyone else, there is really no reason too.

#

Hi

tall temple
#

and how can i define @app.commands ?

#

@slate swan 😹

#

oh i found

#

my bad, thanks for everything

vale wing
austere token
shrewd apex
austere token
#

i need verification bot i got some from chat gpt nothing works found on github still nothig

shrewd apex
#

... so basically ur trying to setup some code without verified source or wether it works?

tall temple
#
@app_commands.checks.has_permissions(Administrator=True)
@bot.slash_command(name="setfee", description="CMD used to set a payment method")
async def setfee(ctx, Payment Method Name : discord.Option(str, "Write Here The Payment Method Name", required = True),info : discord.Option(str, 'Write Here The Payment Method Link / Address ...', required = True), fee : discord.Option(float or int, 'Write Here The Payment Method (extra) Fee (X%)', required = True)) :
#

i want to make the option with spaces, but i get error, could you help me for ?

glad cradle
#

python skill issue

#

you can't have variables with spaces

tall temple
glad cradle
#

i don't think it exist in any programming language

#

you should space using the snake case e.g this_is_a_spaced_var

tall temple
glad cradle
#

you can change it, iirc there was a kw

tall temple
glad cradle
#

lemme check

#

you're using pycord right?

tall temple
#

dpy

glad cradle
#

are you sure?

#

btw it's the name kwarg

tall temple
shrewd apex
# tall temple

the namespaces in half the packages are same thats why u cant have multiple installed at same time

#

with discord libraries

tall temple
#

eh

shrewd apex
tall temple
#

okay

glad cradle
#

he's using pycord

#

i'm pretty sure

tall temple
#
aiohttp==3.8.3
aiosignal==1.3.1
altgraph==0.17.3
anyio==3.6.2
async-timeout==4.0.2
attrs==22.1.0
auto-py-to-exe==2.31.1
bottle==0.12.24
bottle-websocket==0.2.9
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
DateTime==5.0
discord==2.1.0
discord-webhook==1.0.0
discord.py==2.2.2
Eel==0.14.0
Flask==2.2.2
frozenlist==1.3.3
future==0.18.3
gevent==22.10.2
gevent-websocket==0.10.1
greenlet==2.0.2
h11==0.14.0
httpcore==0.16.3
httpsx==0.0.1
httpx==0.23.3
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
MarkupSafe==2.1.2
multidict==6.0.3
pefile==2023.2.7
py-cord==2.4.0
pycparser==2.21
pyinstaller==5.8.0
pyinstaller-hooks-contrib==2023.0
pyparsing==3.0.9
pytz==2022.7.1
pywin32-ctypes==0.2.0
requests==2.28.2
rfc3986==1.5.0
sellpass==1.0
six==1.16.0
sniffio==1.3.0
spark-parser==1.8.9
tls-client==0.1.8
typing_extensions==4.4.0
uncompyle6==3.9.0
urllib3==1.26.14
utils==1.0.1
Werkzeug==2.2.3
whichcraft==0.6.1
xdis==6.0.5
yarl==1.8.2
zope.event==4.6
zope.interface==5.5.2
#

huh

#

both

shrewd apex
#

ur using pycord tho

#

to avoid confusion and namespace clashes

tall temple
#

and what to i have to do for spaces ?

shrewd apex
#

lemme check docs

tall temple
#

okay πŸ«‚

shrewd apex
#

just supply a kwarg name

cinder horizon
vale wing
vocal snow
#

πŸ˜΅β€πŸ’«

tall temple
timid spade
#

can someone tell me how can i get the number of times a member have booster a server?

timid spade
timid spade
tall temple
#

it worked

#

i'm so dumb thanks

timid spade
#

nah its fine

tall temple
timid spade
# tall temple but ?

thats not how it works for slash commands
you should watch a tutorial on yt or search for sample cods

tall temple
#

bruh it just worked 1 hour ago

#

πŸ’€

timid spade
#

huh

tall temple
#

it works for pycord i guess

timid spade
#

yes, i dont know pycord

waxen oriole
#

I need help making a discord bot with making a vc channel that will make more when you join and invite counter

tall temple
timid spade
tall temple
timid spade
#

i am a learner too so cant explain like a professional, but yeah

tall temple
timid spade
#

no i am just waiting for someone better to come and help me 😭

#

anyone know how can i get the number of times a member have booster a server?

tall temple
#

search on py docs :/

#

lemme check 4 you

shrewd apex
#

u can get a message event like where u watch for system messages like this person boosted the server

#

using on_message event

timid spade
shrewd apex
#

there is a message type for that wait a sec

timid spade
shrewd apex
#

u may have version or component conflicts at any moment or update

tall temple
shrewd apex
#

stop using it in your code

tall temple
#

@shrewd apex that's my all imports :

#
import discord, discord.ext
from discord.ext import commands
from discord import app_commands
import time
from colorama import init
from colorama import Fore, Back, Style
import json
tall temple
shrewd apex
#

so the methods you are using will change

#

pick one pycord or discord then solve all the errors

tall temple
shrewd apex
#

bruh by coding and looking at the docs

#

how else?

timid spade
shrewd apex
#

np

timid spade
# shrewd apex np

while coding ofc you test code many times
how do i test codes likes this, i cant boost again and again
is there in alternate way?

shrewd apex
#

and if check is unlikely to be buggy just an equality type check

shrewd apex
#

the main line if check is just this not much to test

#

other than the server or boost channel u setup for the server

timid spade
shrewd apex
#

record the messages

#

message.author is the booster store it in the db

timid spade
#

ok nvm nvm

#

sorry i figured it out

#

thanks tho

tall temple
#

huh

glad cradle
shrewd apex
glad cradle
#

I think it's raising that error because it's discord.py now

#

because pycord has discord.ext.commands.Bot.slash_command, discord.py no

vivid axle
#

how cna i check if someone has nitro

shrewd apex
vivid axle
#

ok

shrewd apex
#

its None if user hasnt boosted

steady flume
#

guys, help me pls with this error:
i make discord bot on replit and when i try to connect to Mongo db - i get this error:

#

ik i need require #databases but maybe someone knows about it

shrewd apex
#

finally make sure the mongo link is correct

steady flume
#

i have it, still error

#

and sometimes it works and sometimes doesnt

steady flume
shrewd apex
#

then its a net issue perhaps due to replits shared network

#

why not code locally

steady flume
shrewd apex
#

use vscode yert

#

or just idle

steady flume
#

btw

#

one guy one time helped me with this advise

#
import dns.resolver

dns.resolver.default_resolver = dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers = ["8.8.8.8"]
#

but it has this issue

#

wait

ornate crater
#

what???

#

actived the badge !

#

what the prob?

shrewd apex
magic whale
#
@code_bot.tree.command()
async def shop(interaction: discord.Interaction, max_coins: int = 1):
    """
    Allows user to buy items on the shop.
    """
    if str(interaction.channel_id) == channel_details[0]['ChannelID']:
        with open("./AddedUsers/AllUsers.txt" , "r") as file:
            all_users_str = file.read()
            all_users_replaced = all_users_str.replace("'", "\"")
            all_users = json.loads(all_users_replaced)
        counter_4 = 0
        for each_user in all_users:
            if str(interaction.user.id) in each_user:
                options = [
                    discord.SelectOption(label='Option 1', value='option1' , emoji="❀️"),
                    discord.SelectOption(label='Option 2', value='option2' , emoji="❀️"),
                    discord.SelectOption(label='Option 3', value='option3' , emoji="❀️")
                ]
                select = discord.ui.Select(options=options, placeholder='Choose a category...', custom_id='category')
                view = discord.ui.View()
                view.add_item(select)
                await interaction.response.send_message(content='Choose a category from the dropdown below! :smiling_imp:', view=view)
            else:
                counter_4 += 1
                
        if counter_4 == len(all_users):
            await interaction.edit_original_response(content="**User Does Not Exist. Please Use  `/add_user`  To Add User.**")

hello i am doing this but i want the bot to send a message when the user selects any of the item in dropdown menu

#

how do i do it?

steady flume
#
await interaction.response.send_message(f"something", ephemeral=True)
magic whale
steady flume
#
if self.values[0] == "<Option Name>":
    await ...
#

[0] - first value

#

[1] - second and etc

#

and it must be in callback event

magic whale
steady flume
#
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "<Option Name>":
    await ...
ornate crater
#

This should run and print this text instead

magic whale
steady flume
magic whale
steady flume
#

ill make example for you

#
async def interaction_check(interaction: discord.Interaction):
        if author == interaction.user.id:
            return True
        else:
            await interaction.response.send_message(f"This menu is not for you", ephemeral=True)
#

ohh soryy

#

incorrect a bit

magic whale
magic whale
#

i said i want to check if the user interacted with any of the items in my dropdown list

#

any one of these. how to check if user selected any one of the options?

steady flume
#

why u need check this ?

magic whale
#

then how am i supposed to display something when user clicks on either one of the boxes????

steady flume
#

You mean this ?

magic whale
#

no

#

select box

#

discord.ui.Select

this one

slate swan
#

how can i make a button only clickable 1 time?
i used button.disable, the button is disabled but is still interactable

flint stirrup
slate swan
simple plume
#

Hi! I have this code, the bot sets up correctly, the permits are correct but he isn't responding to the command..

blissful quest
#

weyo i nedd help

simple plume
blissful quest
#

uhm

#

its say that i not have pillow but i installed it alltime :/

smoky sinew
#

first of all, you can't have two bots running at once (not with .run alone anyway) so remove all the bot = ... stuff

#

then @client.event needs to be before client.run

#

and client needs to have the message content intent

simple plume
#

ty

#

❀️

slate swan
#

how to make tree command bot work in 2 servers like

@tree.command(guild = discord.Object(id=id1 id2)

smoky sinew
#

which is List[Snowflake]

#

e.g. ```py
@bot.tree.command(guilds=[
discord.Object(id=...),
discord.Object(id=...),
discord.Object(id=...)
])

slate swan
#

i made it global

smoky sinew
#

just look on the docs for this information

slate swan
#

eh its okay it was my last update on the bot anyways thumbsup

#

because nothing else left to add it to the bot after 1.7k lines of coding its now done

static bone
#

i made a language translation bot but it's picking up target language code too. One language code works and it gets failed in other languages like worked in ES=Spanish but doesn't work in FR=French or DE=German

#

please help me out

smoky sinew
static bone
#

nope

smoky sinew
#

that's a big coincidence

#

use these two code snippets

static bone
#

i am new to coding please help me out. Where to put these?

naive briar
#

Put what

smoky sinew
#

the code snippets

smoky sinew
#

use @client.command()

slate swan
#

And your expecting people to help you

smoky sinew
sick birch
#

Is it possible to add a persistent view using .add_view without having to instantiate it? I've got a view like so:

class MyView(discord.ui.View):
  def __init__(self, arg1, arg2, arg3) -> None:
    ...

async def setup(bot: Bot) -> None:
  ... # ?

I won't have the appropriate arguments to pass into MyView - but I do believe I actually have to pass in an instance of MyView into .add_view which I don't think I can do. Wondering if there is another way to register persistent views?

hushed galleon
sick birch
hushed galleon
#

if you're sending the view right afterwards, add_view should be redundant

sick birch
#

Jinja2 template is fetched
View is constructed with the proper arguments
View is added using add_view
And it's sent along in a message

hushed galleon
#

why do you want to add the view then? thats done automatically when you send/edit

sick birch
hushed galleon
#

ya, add_view doesnt change that

sick birch
#

Am I misunderstanding the purpose of add_view?

hushed galleon
#

usually you'd store the necessary information for constructing a view in your database then during bot startup, reconstruct and add those views so dpy knows how to dispatch them

#

though it is also possible for a single view to be dispatched across multiple messages if you dont provide add_view(message_id=)

sick birch
#

Unfortunately I don't know the arguments of a view ahead of time, it's sort of dispatched on the fly

#

(It's on a @tasks.loop)

#

For all intents and purposes we get a message with the same view every 60 seconds

smoky sinew
#

why do you need to add_view in the first place? why not just send it

#

oh it's persistent

#

i'm not really sure adding a persistent view every 60 seconds is the best idea though

hushed galleon
#

assuming all the custom ids are the same, you could make your view parameters optional, add one view without a message id, and then retrieve the needed information during your callback

#

though trying to be stateless by inferring it from your message is somewhat annoying of an approach

sick birch
#

Looks like adding the view as I send it doesn't work either (at least not until the bot has first sent the view for the first time on reboot)

#

If it makes any difference I only really need the view to accept parameters so I can pass it down to a modal that's sent when the button is pressed

hushed galleon
sick birch
#

Would be cool if I could just like, pass in a custom ID or something into the add_view

#

Rather than a rich object

hushed galleon
#

if you want to parameterize your components' custom ids you can do that just fine, though i suspect what you actually mean is having dynamic custom ids (e.g. matching by regex) which is a feature that afaik is still in "design purgatory hell", as danny put it

sick birch
#

Oh, no. My custom IDs is static for all buttons of the same type sent out

hushed galleon
#

oh, what do you need to pass a custom id for then? if you want a way to register a callback function, make a wrapper that creates the appropriate component type, sets the custom id and callback, adds it to a view, then adds the view to the bot

sick birch
#

I'm guessing under the hood, the discord API works similarly, right?

#

Either that or a snowflake ID of some sort

hushed galleon
#

uhh, well "views" in dpy is completely their own abstraction

sick birch
#

Right. I believe the IDs do actually exist on the API-level?

hushed galleon
#

discord's api just expects you to give them a custom id for each component, and when a button is clicked you get a payload containing said custom id, but figuring out the correct callback to invoke by yourself is inconvenient

sick birch
#

Oh that makes sense

hushed galleon
#

views abstract that process into a single object that can be added to your bot's internal view store, and once an interaction is received it looks through that store to find which callback to call

sick birch
#

Discord.py couldn't know which class is associated with which custom IDs

#

From nothing but the custom ID, of course

#

Once added to the internal store like you mentioned I suppose it's quite trivial to loop through and figure out which component is associated with which custom ID and what the callback is

hushed galleon
#

use a function that dynamically fetches your prefix

timid spade
#

how do i check if someone has removed only one boost but still is boosting with 2nd boost?

hushed galleon
hushed galleon
smoky sinew
#

what is prefix

#

what is it though

#

like what is the value

#

yeah then it never changes

#

you need to make get_prefix async and use find_one in get_prefix

#

also you should be using motor not pymongo

#

an async python wrapper around mongodb

#

its usage is pretty much the same as pymongo

timid spade
#

i have this on_message event
and when i have it the prefix commands stops working, but as i comment it out they start working again

drifting arrow
#

Is there an inbuilt way to display colors? Like say I want the user to pick between 4 colors, Red, Green, Blue and Yellow. Is there a way to display those as actual colors?

smoky sinew
#

it needs to take message and bot

#

also like i said use motor

#

and you shouldn't override _id

smoky sinew
#

yes

#

you literally just add await everywhere

#

that's about it for migrating from pymongo

#

yes dead ass

ornate crater
#

Why does it say that?

#

please someone help! 😒

#

you should write this

slate swan
ornate crater
#
from discord.ext import commands
from discord import app_commands
import discord

class HelpCMD(commands.Cog):
    def __init__(self, client):
        self.client = client
        
    @app_commands.command(description="Xeton - Parancslista")
    async def help(self, ctx: discord.Integration):

        view = View()

        await ctx.response.send_message(view=view)

class Core(discord.ui.Select):
    def __init__(self):

        options = [
            discord.SelectOption(label="FelhasznΓ‘lΓ³i parancsok", 
                                 description="Alap felhasznΓ‘lΓ³i parancsok")
        ]

        super().__init__(placeholder="VΓ‘lassz ki egy kategΓ³riΓ‘t!", 
                         min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "FelhasznΓ‘lΓ³i parancsok":
            embed = discord.Embed(color=discord.Color.blue())
            embed.set_author(name="Parancslista", icon_url=interaction.user.display_avatar)
            embed.add_field(name="FelhasznΓ‘lΓ³i parancsok", value="**/ping** - Bot ping\n**>avatar (emlΓ­tΓ©s)** - ProfilkΓ©p lekΓ©rΓ©s\n**>botinfo** - Bot informΓ‘ciΓ³k\n**>userinfo (emlΓ­tΓ©s)** FeelhasznΓ‘lΓ³ informΓ‘ciΓ³k\n**>serverinfo** - Szerver informΓ‘ciΓ³k\n**>dc** - Support szerver\n**>invite** - Bot meghΓ­vΓ‘s")
            embed.set_footer(text="Xeton Γ— help")
        
            await interaction.response.send_message(embed=embed)

class View(discord.ui.View):
    def __init__(self):
        super().__init__()

        self.add_item(Core())

async def setup(client):
    await client.add_cog(HelpCMD(client))```
#

@slate swan

#

or someone

stiff olive
#

Hi

ornate crater
#

Hey

naive briar
#

It's probably just Discord saying that you can get an active dev badge 🀷

#

From what I see in that image anyway

stiff olive
#
lol = f"{packtitle}-{rv}.zip"
await interaction.response.send_message(content="Preparing AVPBR Retextured...", file=lol, ephemeral=True)```
#

I'm trying to do this

#

and im getting

#
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "C:\Users\lux\Desktop\jojobot\bot.py", line 87, in download
    await interaction.response.send_message(content="Preparing AVPBR Retextured...", file=lol, ephemeral=True)
  File "C:\Python\lib\site-packages\discord\interactions.py", line 763, in send_message
    params = interaction_message_response_params(
  File "C:\Python\lib\site-packages\discord\webhook\async_.py", line 606, in interaction_message_response_params
    attachments_payload.append(attachment.to_dict())
AttributeError: 'str' object has no attribute 'to_dict'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'download' raised an exception: AttributeError: 'str' object has no attribute 'to_dict'```
slate swan
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
stiff olive
#

Sending that doesn't help.

#

I've already looked at it.

slate swan
#

im sending that for myself

stiff olive
#

Oh πŸ’€

slate swan
#

to see that file should be File object

#

not string

shrewd fjord
#

ttachments_payload.append(attachment.to_dict())
AttributeError: 'str' object has no attribute 'to_dict'

stiff olive
#

ow do

shrewd fjord
#

what's "lol"

stiff olive
#

a random variable

shrewd fjord
#

u need to use!d discord.File

#

!d discord.File

unkempt canyonBOT
#

class discord.File(fp, filename=None, *, spoiler=..., description=None)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.

Note

File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
stiff olive
#

?

shrewd fjord
#

file=discord.File("path-to-file")

stiff olive
#

o

#

wtf

shrewd fjord
#

πŸ’€

stiff olive
#

ok

#

how do I prevent interaction timeout?

slate swan
#

defer it

shrewd fjord
slate swan
#

put await interaction.response.defer() at the top of your command

shrewd fjord
#

if you want to send more messaged, you might need to followup it

stiff olive
#

Ah

#

so interaction.response.defer()

slate swan
stiff olive
#

at the top?

slate swan
#

first line of the command

shrewd fjord
#

you can add thinking=True too iirc

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

!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
shrewd fjord
#

yeah u can

stiff olive
#
  File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "C:\Users\lux\Desktop\jojobot\bot.py", line 87, in download
    await interaction.response.send_message(content="Preparing AVPBR Retextured...", file=discord.File(f"{packtitle}-{rv}.zip"), ephemeral=True)
  File "C:\Python\lib\site-packages\discord\interactions.py", line 751, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Python\lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'download' raised an exception: InteractionResponded: This interaction has already been responded to before
slate swan
#

you need to followup

stiff olive
#

??

slate swan
#

not response

stiff olive
#

followup

shrewd fjord
#

you now nee to followup\

#

!d discord.Interaction.followup

unkempt canyonBOT
shrewd fjord
#

doesnt work for some reason

slate swan
#

well

#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks") and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ForumChannel.webhooks "discord.ForumChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
shrewd fjord
#

its awat interaction.followup.send(...)

stiff olive
#

oh

#

followup.send

shrewd fjord
slate swan
#

yeah its .send

stiff olive
#

hot men

#

discord py or js?

#

Are you saying python or mocking it.

quick umbra
#

user: discord.Member

ornate crater
#

bannedsungl

slate swan
maiden fable
#

Why was I expecting the emoji name to be Down

slate swan
maiden fable
#

I'm out

cloud dawn
tall temple
#

how to let people with admin perms only execute a cmd ?

hushed galleon
#

are you using pycord or discord.py? and is it for a text command or a slash command

#

dpy text command: @commands.has_permissions() or @commands.has_guild_permissions()
dpy slash command:

  • @app_commands.default_permissions() to configure a default permission requirement for members to see the command, though server admin can change this
  • @app_commands.checks.has_permissions() if you want to enforce that requirement regardless of what the server admin sets it to
    pycord text command: same as dpy
    pycord slash command: couldnt figure that out from a quick look through their docs
hushed galleon
#

but no has_permissions() equivalent

tall temple
hushed galleon
#

thats not a thing when you're using default_permissions, after syncing your command with that decorator, discord will make the command completely unusable to people that dont have the permission

tall temple
#

oh yeah i just saw this

#

tysm @hushed galleon you're a crack πŸ«‚

static bone
blissful badge
#

Trying to figure out why my slash commands aren't working, anything look incorrect in here to anyone?

import os
import discord
import discord.ext
from discord.utils import get
from discord.ext import commands
from discord import app_commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.all()
intents.message_content = True
intents.members = True 

extensions = ("embed","joinleave","moderation","responses", "reactions", "gameservers",)
bot = commands.Bot(command_prefix="?", intents=intents)
ALLOWED_GUILDS = (left blank in example,)
bot.add_check(lambda ctx: ctx.guild.id in ALLOWED_GUILDS)
ALLOWED_ROLES = (left blank in example,)
bot.add_check(lambda ctx:
any([r in ctx.author._roles for r in ALLOWED_ROLES]))

@bot.event
async def setup_hook():
    for extension in extensions:
        await bot.load_extension(extension)

@bot.event
async def on_ready():
    await bot.tree.sync(guild=discord.Object(id=709208493684555858))
    print("Ready!")

@bot.event
async def on_ready():
    print("Turlington is online and watching!")
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="the servers."))

bot.run(TOKEN)
#

By not working I mean they aren't even showing up as options when prompting with the / in discord

maiden fable
#

Slash commands take time to register and show up

#

Discord issue 🀷

blissful badge
#

I am fine waiting if it will take longer just not sure if its supposed to take that long

maiden fable
#

If it would have been 12 minutes then it would be normal πŸ˜…

blissful badge
maiden fable
#

Yea.... but sorry can't really help u I never used app commands with dpy

blissful badge
#

As far as I can tell everything is right, and it throws zero errors...but isn't working.

maiden fable
#

I would be happy to take a look at the code but it will take some time since I'm away from my laptop

blissful badge
north kiln
#

why do you have 2 on_ready events tho

blissful badge
#

I guess I can merge them

north kiln
#

you shouldn't sync your tree on_ready

blissful badge
#

Oh

#

Thats the only way I know how to do it

north kiln
#

from what I have heard syncing with a normal text command is better

blissful badge
#

Which is fine, just wanna make sure I understand

north kiln
#

yeah

ashen locust
#

i have installed discord but it still happens

north kiln
#

from discord.ext import commands

ashen locust
#

thanks

mighty sun
#

Hello, I can't find the way to write the numbers like this, for example, at the moment he writes like this: 10000000 and I would like him to write like this: 1 000 000, I don't know how to do it...can you help me please?

#
__expr = {
        'qty': re.compile('\(x\d+\)'),
        'seller': re.compile('``[\w_]{3,48}``'),
        'item': re.compile('nte ``.{1,32}`` \('),
        'price': re.compile('\*\*[\d\s]+✸\*\*$')
    }
blissful badge
# north kiln yeah
@bot.command()
async def sync(ctx,):
    await bot.tree.sync(guild=discord.Object(id=709208493684555858))
    await ctx.send("Slash commands have been synced with Discord.")
#

This look ok?

north kiln
#

it works I guess? should add an owner check tho

blissful badge
north kiln
#

so not anyone can use this?

blissful badge
#

Well the slash commands aren't working anyways, so theres something wrong elsewhere

blissful badge
#

So thats taken care of anyways

north kiln
#

no

#

only you should have the right to sync

#

not any other ppl

blissful badge
#

I guess thats fair

#

Ok I will fix that

blissful badge
# north kiln not any other ppl
@bot.command()
async def sync(ctx,):
    if ctx.message.author.id =='288522211164160010':
        await bot.tree.sync(guild=discord.Object(id=709208493684555858))
        await ctx.send("Slash commands have been synced with Discord.")
    else:
        await ctx.send("Sorry, you dont have the required permissions to perform this command!")

Look better?

#

Oh

#

Thats telling me I don't have permission to use it, wtf lol

#

oh I had the ' ' still nvm

blissful badge
gusty flax
# blissful badge Please do
@commands.command()
    @commands.guild_only()
    @commands.is_owner()
    async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object],
                   spec: Optional[Literal["~", "*", "^"]] = None) -> None:
        if not guilds:
            if spec == "~":
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "*":
                ctx.bot.tree.copy_global_to(guild=ctx.guild)
                synced = await ctx.bot.tree.sync(guild=ctx.guild)
            elif spec == "^":
                ctx.bot.tree.clear_commands(guild=ctx.guild)
                await ctx.bot.tree.sync(guild=ctx.guild)
                synced = []
            else:
                synced = await ctx.bot.tree.sync()

            await ctx.send(
                f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
            )
            return

        ret = 0
        for guild in guilds:
            try:
                await ctx.bot.tree.sync(guild=guild)
            except discord.HTTPException:
                pass
            else:
                ret += 1

        await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")```
blissful badge
#

So most of that makes sense but what is the optional section doing for me?

#

Just trying to understand

#

Also if this is just going into my base file I would just translate it to @bot.command() correct?

#

@gusty flax gives this File "C:\Users\PrimaryBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 691, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

#

Seems I had to remove self from it

#

THAT WORKED!

#

Slash commands function now.

#

Do I just need to set a universal response so it doesn't do this?

nova remnant
#

How can I get what the user is playing right now? I can only find out the user status but not what game he is playing

smoky sinew
#

this is so pointless

blissful badge
#

I don't like relying on additional modules so this works better for me

fading egret
#

how can i load the commands in multiple guilds?
a list doesnt work obiously..

await bot.add_cog(key(bot), guilds=[discord.Object(id=267624335836053506)])

smoky sinew
#

oh you mean group cog

#

guilds= should work

fading egret
smoky sinew
#

you don't

#

it's a list of objects

fading egret
# smoky sinew you don't

but when i put

await bot.add_cog(key(bot), guilds=[267624335836053506, 336642139381301249]

it just returns

discord.ext.commands.errors.ExtensionFailed: Extension 'keySystem.create_key' raised an error: AttributeError: 'int' object has no attribute 'id'

smoky sinew
#

it's not a list of integers

#

it's a list of objects

#

you just put multiple objects in the list

fading egret
magic whale
#

hello how can i make the callback of a select menu to be sent inside the origional response?

smoky sinew
unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
stiff olive
#

How do I make it show that response

#

basically, "you are missing this role"

#

aka

#

like error response or else statement

hushed galleon
#

use CommandTree.error() to add your own error handler, then check for the exceptions you're interested in and send an appropriate response

stiff olive
#

huh

#

like

#
@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: discord.app_commands.AppCommandError) -> None:```
hushed galleon
#

yup

stiff olive
#

so what would be

#

errors.wrongpermissions

#

and where should that go?

hushed galleon
#

you could literally write if isinstance(error, discord.app_commands.errors.MissingAnyRole): ... in this case, but assuming you have app_commands imported the shorter form would be if isinstance(error, app_commands.MissingAnyRole):

#

make sure if you dont know how to respond to the error that you print the traceback, otherwise you'll hide error messages when your commands fail

stiff olive
#

It's only for one command overall anyway

#

So I just need the response for one command

#
@client.tree.command(name="dl")
@app_commands.describe(pack=cmddesc)
@app_commands.checks.has_any_role(762044720762716190, 762044945233739816, 762045678426914906)```
hushed galleon
#

there is a @error decorator provided by individual commands, but for handling check exceptions its more convenient to use the global tree handler in case you later have more commands using the same check

hushed galleon
#

!d discord.app_commands.Command.error

unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

The local error handler is called whenever an exception is raised in the body of the command or during handling of the command. The error handler must take 2 parameters, the interaction and the error.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
stiff olive
#

and for the global

hushed galleon
#

thats what i showed you earlier

stiff olive
#

would it be like

#

cause I want to add a cooldown

hushed galleon
#

yeah that seems about fine

#

i mean, the if statement's fine but you also should print the traceback if you dont have a response for the error

stiff olive
#

traceback?

#

I don't use python, I'm a c++ person

hushed galleon
#

!traceback

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

stiff olive
#

I'm just going off brain power LOL

hushed galleon
#

use traceback.print_exception() if you want to be fancy

stiff olive
#

ah

hushed galleon
#

and raise error if you want to be lazy

stiff olive
#

@discord.app_commands.Command.error()

#

omg i'm SO LOST

hushed galleon
#

the command() decorator transforms your function into a Command object, thats where you'd access the error method from

#
@tree.command()
async def my_command(interaction): ...

@my_command.error
async def my_command_error(interaction, error): ...```
stiff olive
#
@client.tree.command(name="dl")
@app_commands.describe(pack=cmddesc)
@app_commands.checks.has_any_role(762044720762716190, 762044945233739816, 762045678426914906)

@client.dl.error
async def error():
    print("You need the Early Access role to use this command.")```
#

line 92, in <module>
@client.dl.error
AttributeError: 'Bot' object has no attribute 'dl'

#

oh wait

stiff olive
#

figured it out

#

I had to put it after the definition

#

error() takes 0 positional arguments but 2 were given
πŸ’€

#

interation

#

and then error

#

I'm so lost

#

I wish there was an example πŸ’€

glad cradle
#

what's the error now

outer parcel
#

Is there any way i can udpate the choices in real time in the code

#

because it seems i just cant udpate them

magic whale
#

my select menu shows interaction failed even when i interact with it how do i fix it?

stiff olive
#

figured it out

#

πŸ’€

smoky sinew
#

use a custom autocomplete

outer parcel
#

i did that

smoky sinew
outer parcel
#

but there is error

smoky sinew
#

did you look at the example

magic whale
#

my select menu shows interaction failed even when i interact with it how do i fix it?

magic whale
# smoky sinew what's your code
@CodeBot.tree.command()
async def shop(ShopInter: discord.Interaction , max_coins: int = 1):
    """
    Allows user to buy items on the shop.
    """
    with open("./ServerDetails/AllData.txt" , "r") as file:
        # Getting the id of channel that user has selected for the shop:
        DetailsStr = file.read()
        DetailsRep = DetailsStr.replace("'", "\"")
        ChannelDetails = json.loads(DetailsRep)
        
    # Checking if the user has used the command in specified channel:
    if str(ShopInter.channel_id) == (ChannelDetails[0]['ChannelID']):
        await ShopInter.response.send_message(f"**Please Wait Loading Categories For You...**")
        
        # Getting all the existing users in our database:
        async def CategoryLoader():
            with open("./AddedUsers/AllUsers.txt" , "r") as file:
                UsersStr = file.read()
                UsersRep = UsersStr.replace("'" , "\"")
                AllUsers = json.loads(UsersRep)
                
            Counter = 0
            # Checking if user exists in our database:
            for EachUser in AllUsers:
                # If user exists in database then showing him the shop:
                if (str(ShopInter.user.id)) in EachUser:
                    
                    async def CatViewCallback(interaction):
                        await interaction.response.defer()
                        await ShopInter.edit_original_response(content=f"This is a test for: {CategorySelect.values[0]}")
                    
                    CategorySelect = CategoryDropdown()
                    CategorySelect.callback = CatViewCallback
                    CategoryView = discord.ui.View()
                    CategoryView.add_item(CategorySelect)
                    await ShopInter.edit_original_response(content=f"Choose A Category From Dropdown Below..." , view=CategoryView)
                    
                else:
                    Counter += 1
                    
            # If user doesn't exist in database after checking it completely then telling him to register:
            if Counter == len(AllUsers):
                await ShopInter.edit_original_response(content=f"**User Does Not Exist. Please Use  `/create_account`  To Add User.**")
                
        ViewCategory = await CategoryLoader()
smoky sinew
#

i don't know what CatViewCallback is

#

oh wait

#

yeah don't use defer

outer parcel
smoky sinew
#

edit_original_response is not technically a response

#

you need interaction.response.edit_message

magic whale
#

when i use it it doesn't

smoky sinew
#

delete both lines and add interaction.response.edit_message

magic whale
magic whale
#

it worked like charm. thanks alot

tall temple
#

how can i make slash commands options to pick channels

#

like xenon

slate swan
#

how do i make a slash command to generate
like
/generate apikey: mhs54d89g7asdufji

#

pretty mcuh like these options things

smoky sinew
unkempt canyonBOT
#

class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.

Please note that if you use this in a private message with a user, no channels will be displayed to the user.

New in version 2.1.
smoky sinew
slate swan
#

thanks

smoky sinew
#

if you're using a cog this is pretty much what you need to make a required argument

#

just make sure to sync slash commands if this is your first time making a command

tall temple
slate swan
smoky sinew
#

i don't know what that is

#

PyExecJS (EOL)
End of life
This library is no longer maintananced. Bugs are not be fixed (even if they are trivial or essential).

We suggest to use other library or to make a fork.

#

this?

fading egret
#

is there a error handler which handles all errors of the slash commands in a cog?

#

so not only command_name.error() but for everything

slate swan
#

im usuing nextcord and menus.ButtonMenuPages, how would i send this to another channel, this doesnt work
AttributeError: 'TextChannel' object has no attribute 'bot'

pages = CustomButtonMenuPages(source=MyEmbedFieldPageSource(list))
channel = bot.get_channel(1096435088775979078)
await pages.start(channel)
smoky sinew
#

!d discord.app_commands.CommandTree.error

unkempt canyonBOT
#

@error(coro)```
A decorator that registers a coroutine as a local error handler.

This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.

The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
tall temple
#
@bot.slash_command(name="setlogs", description="CMD used to set logs channel")
smoky sinew
#

no i do not know pycord

tall temple
#

eh

smoky sinew
#

but i imagine the select system is pretty similar

tall temple
#

okok

fading egret
tall temple
quick umbra
smoky sinew
fading egret
thin raft
#

How do I disable a button

#

button.disabled = True

#

doesn't seem to work

slate swan
#

can it execute discord.js

#

i use it for fingerprinting things

import execjs

package_pwd_script = open("tasks/packagepwd.js").read()
script = execjs.compile(package_pwd_script)


def package_pwd(password, random_num, key):
    pwd = script.call("encrypt", password, random_num, key)
    return pwd
#

can anyone help me
AttributeError: 'CustomButtonMenuPages' object has no attribute '_state'
im getting this error when trying to start a tasks.loop in a specific channel:

pages = CustomButtonMenuPages(source=MyEmbedFieldPageSource(list))
await pages.start(ctx=None, interaction=pages, channel=channel)

smoky sinew
thin raft
smoky sinew
#

you have to update the message

thin raft
#

await interaction.message.edit(view = self)

smoky sinew
#

yeah

smoky sinew
#

why not just port the javascript code to python

slate swan
young dagger
#

Would you guys use the first or second example?
1.

player_team_id = next((p['teamId'] for p in match_data['info']['participants'] if p['puuid'] == summoner_puuid), None)
if player_team_id is None:
    continue```
2.
```python
        for participant in match_data['info']['participants']:
            if participant['puuid'] == summoner_puuid:
                player_team_id = participant['teamId']
                break
        else:
            continue```
slate swan
young dagger
#

Doesn't continue mean it will loop endlessly?

#
if player_team_id is None:
    continue```
slate swan
#

yeah now they do in fact the same thing

#

only difference is in the syntax, choose which one you want

young dagger
#

Oh wait it's inside another loop so it will actually skip that particular match and go to the next one.


for match_id in match_ids:
    player_team_id = next((p['teamId'] for p in match_data['info']['participants'] if p['puuid'] == summoner_puuid),
                              None)
        if player_team_id is None:
            continue```
#

Nvm thanks @slate swan

slate swan
#

np, only if it doesn't find it it's None

#

else not

young dagger
#

Here is the full code:

    for match_id in match_ids:
        url = f'https://europe.api.riotgames.com/lol/match/v5/matches/{match_id}'
        headers = {'X-Riot-Token': api_key}
        async with rate_limit:  # use AsyncLimiter
            async with aiohttp.ClientSession(headers=headers) as session:
                async with session.get(url) as response:
                    if response.status == 200:
                        await asyncio.sleep(0.3)  # add 0.3 second delay
                        match_data = await response.json()
                    else:
                        await asyncio.sleep(0.3)  # add 0.3 second delay
                        return None

        player_team_id = next((p['teamId'] for p in match_data['info']['participants'] if p['puuid'] == summoner_puuid),
                              None)
        if player_team_id is None:
            continue```
slate swan
young dagger
#

!p

unkempt canyonBOT
#
Missing required argument

pep_number

#
Command Help

!pep <pep_number>
Can also use: get_pep, p

Fetches information about a PEP and sends it to the channel.

young dagger
#

!pastebin

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

np i'll look into rq

thin raft
#

How can I use a custom emoji for a discordpy button

slate swan
#

@young dagger yeah the code is right, if it returns None it will skip this iteration for the generator expression next until it finds an id

#

and also it will create another request for the other ids

slate swan
thin raft
#

I used the >:name:id>

turbid condor
#

Then it might not be settable

#

Custom emojis work in embed description and messages

#

As for buttons I don't think they work only unicode emojis work

slate swan
#

nope you can definitely use custom emojis in buttons

slate swan
timid spade
#

i have this on_message event
and when i have it the prefix commands stops working, but as i comment it out they start working again

thin raft
#

Ir worked

slate swan
timid spade
#

will it fix it?

async def on_message(message):
    if message.content.startswith('prefix'): 
        return  
slate swan
slate swan
timid spade
slate swan
#

what do you mean

timid spade
#

slash commands? you mean this

#

np

slate swan
#

no, it's not a normal prefix, if you want to use it you have to invite your bot with the application.commands scope

#

and then the required decorator and stuff

timid spade
#

anyone know how can a make something like a question and answers system?
you can say like the bot will ask a question on running a command and then look for all the messages in that channel and if in 10 seconds someone's text matches with the actual answer the command will stop by sending a message like "you won".
will it be like adding a on_message event inside a command or something?

slate swan
#

whatever lib you're using here is an example of that

#

i recommend doing it in a command and not in on_medsage

smoky sinew
timid spade
smoky sinew
#

just add a check

#

can you show your current code

timid spade
# smoky sinew can you show your current code
@client.command()
async def flag(ctx):
    data = get_any_flag()
    await ctx.send(f"https://flagcdn.com/256x192/{data[0].lower()}.png")
    print(data) #ignore
    channel = ctx.channel
    def check(m):
        return m.content == data[1].lower and m.channel == channel
    try:
        msg = await client.wait_for('message', timeout = 20.0, check=check)
    
    except asyncio.TimeoutError:
        await channel.send("you lost")
    else:
        await channel.send("you won")```
#

discord makes it look disgusting so here is a pic too

smoky sinew
#

that would be your issue

timid spade
#

thanks you are right

slow ether
#

Hello there! Can You make like /upload In My bot that It Upload a File From My Pc?

slow ether
#

Like Make /upload it open file brower you choose from your pc then enter and then this photo/anything you choose will set to a var

crude nexus
#

im trying to make an offline command for my bot
it doesnt seem to work though and the bot remains online

sick birch
#

You might be able to get the bot to download an attachment a user sent and use that, though

smoky sinew
smoky sinew
crude nexus
#

oh, they cant? so i can only do shutdown?

sick birch
#

Starting and stopping your bot really should not be managed from the bot itself

#

I guess you could but it's probably the job of whatever process manager you're using

slow ether
smoky sinew
crude nexus
#

not really, i would just like it to go offline so i can edit the code

crude nexus