#discord-bots

1 messages · Page 268 of 1

versed zodiac
#

await can only be used in sync

slate swan
#

you cant use await in normal function

fiery jetty
#

Can anyone suggest good Instagram scaping libraries?
(Which are legal)

versed zodiac
#

i get this error

slate swan
#

make it asynchronous function

slate swan
versed zodiac
#
async def setup(bot):
    await bot.add_cog(CommandHandler(bot))```
#

you mean like this

slate swan
fiery jetty
versed zodiac
#

commands do not work

slate swan
versed zodiac
#

@slate swan can you check my github repo if my now

versed zodiac
slate swan
versed zodiac
# slate swan show command code
@bot.command()
async def ping(ctx):
    # Calculate message latency
    message_latency = round(bot.latency * 1000)

    # Calculate message round trip latency
    before = time.monotonic()
    message = await ctx.send("Calculating...")
    after = time.monotonic()
    round_trip_latency = round((after - before) * 1000)

    # Calculate shard latency
    shard_latency = round(bot.latency * 1000)

    # Create and send the latency embed
    embed = discord.Embed(title="Latency", color=discord.Color.blue())
    embed.add_field(name="Message Latency", value=f"{message_latency}ms")
    embed.add_field(name="Message Round Trip", value=f"{round_trip_latency}ms")
    embed.add_field(name="Shard Latency", value=f"{shard_latency}ms")

    await message.edit(content=None, embed=embed)```
slate swan
versed zodiac
slate swan
#

you have message_content intent enabled?

versed zodiac
slate swan
#

you have to enable it in code too

versed zodiac
#

too

#
bot = commands.Bot(command_prefix='.', intents=discord.Intents.all())
slate swan
#

you have that code on github so i can see it?

#

how would the best way be to check if an item for my economy bot needs to be used against another player? should i add another column in my database and do research based on that?

versed zodiac
vocal snow
#

is this just a boolean value?

slate swan
#

like say i have an item that i can use to rob them with a 100% success rate i dont want to use that on myself just another user

#

yeah if i understood correctly i would add another column to database with boolean type

#

okay cool thanks for the info

#

already onto 8 columns about to add 9th

chrome veldt
#

is the discord bot api just a package?

slate swan
#

the most known one in python is discord.py

unkempt canyonBOT
chrome veldt
#

alr

#

thx

sick birch
# chrome veldt is the discord bot api just a package?

The Discord Bot API is a RESTful web API being hosted by Discord under the https://discord.com/api/v10 URL, you sent HTTP requests there to do different actions (like send message, etc)

But the Discord API is complex and you really don't want to make bots by doing that - so packages like discord.py do the hard work for you and give you a nice, Pythonic interface to interact with Discord

versed zodiac
slate swan
versed zodiac
#

so there is surely no problem with the message intent

slate swan
#

so when you do .ping it wont respond?

#

why you use bot.start?

#

instead of bot.run

versed zodiac
#

well indeed the doesen't even dms me for restaed

slate swan
#

show full output of the console

versed zodiac
#

ython/Python Projects/discord bot/main.py"
Bot connected to Discord.
Bot logged in as Krack

Extensions loaded successfully

slate swan
#

how about you replace ```diff

  • @bot.event
  • async def on_message(message):
  • @bot.listen()
  • async def on_message(message):
versed zodiac
#

alright

#

2023-07-10 22:39:29 INFO discord.client logging in using static token
2023-07-10 22:39:55 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 5a87d0d311e837abe0771d80275e92a4).
Bot connected to Discord.
Bot logged in as Krack

Extensions loaded successfully

#

GG!

versed zodiac
slate swan
#

cool

versed zodiac
slate swan
#

👍

versed zodiac
#

whats the logic for shards

#

like wick says shards 1 or 0

chrome veldt
#

whats its name xd

slate swan
#

this is only warning for now does it work when you run it?

chrome veldt
#

i have installed it

slate swan
#

you installed what

chrome veldt
#

unless i did it wrong

slate swan
#

do pip show discord.py

chrome veldt
#

still doesnt workj

#

unleess i instaled it wrong

slate swan
#

it wont work still when you do pip show discord.py i want to see output of this command

chrome veldt
slate swan
#

do python --version

chrome veldt
#

3.11.4

slate swan
#

in vs code do ctrl shift p search for Python interpreter and set it to 3.11.4

chrome veldt
#

works

#

ig i was stuck on the wrong interpreter

#

alr so whats the basics like say i wanted a simple command that just messages hello world

chrome veldt
#

thx

#

im looking on the dev portal and its talking about games and not bots

tall temple
#

can we make member selector for modal ?

chrome veldt
#

which do i pick client or bot... i dont know what is for what

#

oh nvm

slate swan
sick birch
#

Yeah you probably want bot

chrome veldt
#

i will

#

now how exactly do i make the bot active

#

do i just run the program or is there some extra steps to keep it active

slate swan
#

you run the script

#

but to make it online you have to keep the script running obviously

#

so if you want the bot to be 24/7 you need some kind of hosting or vps

chrome veldt
slate swan
chrome veldt
#

cool

tall temple
slate swan
#

why do you need interactions

#

its discontinued isnt it

tall temple
#

i found that tutorial on ytb

slate swan
#

tutorial on youtube explains it all

tall temple
#

bruh

slate swan
#

thats why pycord is bad it does not support everything

tall temple
#

oh

slate swan
#

also there are modals in pycord

tall temple
#

ok thx

thin raft
#

@slate swan

#

the website for learning dpy

#

is contributable?

slate swan
#

add me to friends and ill msg you

thin raft
#

oki

tall temple
#
Traceback (most recent call last):
  File "F:\mesdraps\vouches_bot\main.py", line 29, in <module>
    async def feedback(ctx, interaction : discord.Interaction) :
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 887, in decorator
    command = Command(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 666, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 374, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 834, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 793, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>```
#
import discord
from discord.ext import commands
from discord import ui
from colorama import init
from colorama import Fore, Back, Style
import json
import os, glob
import shutil
import pathlib


config = json.load(open("config.json"))
init()
bot = commands.Bot(command_prefix = "#", intents = discord.Intents.all())



############################################################################################### 



class Mdl(discord.ui.Modal, title = "Submit a feedback") :
    product = discord.ui.TextInput( label = "Product :",
                                    placeholder = "Mention here the product you bought",
                                    required = True)


@bot.tree.command()
async def feedback(ctx, interaction : discord.Interaction) :
    modall = Mdl()
    await interaction.response.send_modal(modall)


bot.run(config['bot_token'])
tall temple
#

alr

tall temple
chrome veldt
chrome veldt
#

any

#

but i firged it out

slate swan
#

ah okay

tall temple
slate swan
tall temple
slate swan
#

Create a command sync and do await ctx.bot.tree.sync()

#

make it prefixed command

tall temple
#

oh ok

#

@slate swan btw can i make an interaction.response.send_modal with a simple prefixed command ?

slate swan
#

no cause you get interaction only with slash commands

tall temple
#

oh ok

chrome veldt
#

how do i use/get a argument

#

like:
command (argument)

slate swan
#
@bot.command()
async def super_command(ctx, argument1, argument2):
    ...
tall temple
#
import discord
from discord.ext import commands
from discord import app_commands
from discord import ui
from colorama import init
from colorama import Fore, Back, Style
import json
import os, glob
import shutil
import pathlib


config = json.load(open("config.json"))
init()
bot = commands.Bot(command_prefix = "#", intents = discord.Intents.all())


@bot.event
async def on_ready():
    print(f'Bot Name: {bot.user}')
    for server in bot.guilds:
        await bot.tree.sync(guild=discord.Object(id=server.id))

############################################################################################### 



class Mdl(discord.ui.Modal, title = "Submit a feedback") :
    product = discord.ui.TextInput( label = "Product :",
                                    placeholder = "Mention here the product you bought [ EX. : 3 months Server Boosts ]",
                                    required = True)


@bot.tree.command(name = "feedback", description = "")
async def feedback(interaction) :
    modall = Mdl()
    await interaction.response.send_modal(modall)


bot.run(config['bot_token'])
#

i cannot even find the slash command lmfao

slate swan
#
    for server in bot.guilds:
        await bot.tree.sync(guild=discord.Object(id=server.id))
``` this wont work
tall temple
tall temple
#

okk

tall temple
# slate swan .
@bot.command()
async def sync(ctx) :
    await ctx.bot.tree.sync()
#

??

slate swan
#

exactly

#

tias moment

#

then when you run the bot run this command

tall temple
#

okay

tall temple
slate swan
#

command should be there

tall temple
slate swan
#

yes

tall temple
#

feedback command

#

oh ok

tall temple
eternal shuttle
#

hi, how do i fix this?

slate swan
#

put in id of your testing server

eternal shuttle
#

why dont u try using something like

#

@bot.event
async def on_ready():
print(f'{bot.user} is now connected to Discord!')
await bot.change_presence(activity=discord.Game(name=f"use '!commandshelp' for a list of all the commands!"))
try:
synced = await bot.tree.sync()
print(f"Synced {len(synced)}command(s)")
except Exception as e:
print(e)

@bot.tree.command(name="commands")
async def commands(interaction: discord.Interaction):
await interaction.response.send_message(f"This Will be the commands help thingy")

tall temple
#

okok

slate swan
tall temple
#

not working

@bot.command()
async def sync(ctx) :
    await ctx.bot.tree.sync(guild=discord.Object(1101820707085754519))```
slate swan
#

or just put it in print

eternal shuttle
#

i just realized that

tall temple
slate swan
#

print(await ctx.bot.tree.sync(guild=discord.Object(1101820707085754519)))

tall temple
#

oh ok

#

nothing occurs in the terminal @slate swan

slate swan
#

did you run the command?

tall temple
#

yeah

slate swan
#

it must have printed something

#

at least empty list []

#

are you sure the command is being invoked

tall temple
#

#sync

slate swan
#

do #help

tall temple
slate swan
#

so it does print something

tall temple
slate swan
#

set the description for your slash command

tall temple
frigid estuary
#

Whats wrong...

#

Help?

slate swan
#

as it tells you

#

!d datetime.datetime

unkempt canyonBOT
#

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
slate swan
#

it takes year month and day but they must be int you have str

frigid estuary
slate swan
frigid estuary
#

so I can just put (class) where I have (datetime)?

slate swan
#

copy pasting random lines from documentation is not the solution

#

i would learn python basics and then come back to this project

left dew
warm jackal
#

what should i know before i make a bot for the first time?

#

like what is the best thing to use

potent spear
#

this might not be up-to-date, but can still be relevant

warm jackal
#

yeah OOP is hard to tackle

#

do u have to pay to run a bot

sick birch
#

Or if you have an old machine you can use that too

warm jackal
#

damn i don’t have an old machine to use

#

hmm

#

if i run it on the machine im currently using will it explode

queen spindle
#

discord.client logging in using static token what is this

hazy spear
#

@warm jackal if im not wrong i think heroku can host it

warm jackal
#

okay

hazy spear
#

theres probably some youtube videos that shows you how to set it up and stuff

#

Traceback (most recent call last): File "C:\Users\Melih\Desktop\discbot\bot.py", line 16, in <module> client.run(TOKEN) File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 668, in run return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 647, in runner await self.start(*args, **kwargs) File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 611, in start await self.connect(reconnect=reconnect) File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 552, in connect raise PrivilegedIntentsRequired(exc.shard_id) from None discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

#

why do i get this error?

tall temple
#

please how can i make a slash command discord.Option(discord.Member, "") but to select members with a specific role ?

hazy spear
#

nvm i fixed mine

hazy spear
#

Traceback (most recent call last): File "C:\Users\Melih\Desktop\discbot\bot.py", line 5, in <module> from discord.ext import commands File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\__init__.py", line 19, in <module> from .flags import * File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 73, in <module> @dataclass ^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1230, in dataclass return wrap(cls) ^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1220, in wrap return _process_class(cls, init, repr, eq, order, unsafe_hash, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 958, in _process_class cls_fields.append(_get_field(cls, name, type, kw_only)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Melih\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 815, in _get_field raise ValueError(f'mutable default {type(f.default)} for field ' ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory

#

hi how can i fix this?

dapper vapor
#

C:\Users\Documents>python script.py
File "C:\Users\Documents\script.py", line 159
return "I apologize, but I don't have the answer to that question at the moment. Could you please ask me something else?"
^
IndentationError: unindent does not match any outer indentation level

torn solar
#

bruh my mom got me a rasberry pi and all it has is the power cable

#

can i even use it

#

like i have no mini hdmi cables or heat things for it

warm jackal
#

is there a way to make it so the bot will say any input you give it live, without your inputs appearing?

#

or using a private channel to type in where the output is in another channel

idle surge
#

Hey, im trying to send a auto message but having trouble. Dont know how to start the loop. This is what I have.

@tasks.loop(seconds=10)
async def auto_send():
    channel = vini.get_channel(1123454159543357540)
    embed = discord.Embed(colour=0x182D9F)
    embed.set_author(name="Just Some Subtle Reminders")
    embed.description = f"-n Be sure to use `.register` to register yourself to earn **Raneon** and buy **rewards**! \n *Do .help in #┃commands \n \n Learn how to join our team over here #┃how-to-join"
    embed.set_image(url="https://cdn.discordapp.com/attachments/1074138997498052760/1125310614147973130/HEADER_22.png")
    await channel.send(embed=embed, delete_after=60)
red mesa
#

why my bot is not getting hosted

turbid condor
idle surge
turbid condor
#

In your code

naive briar
rugged shadow
#

damn does anyone remember okimii 😔

midnight oracle
vocal snow
#

enable message content intent

#

!intents

midnight oracle
#

Where?

#

In the chat?

vocal snow
#

yes

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, 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

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

vocal snow
#

you need to enable them in your code and your dev portal ^

midnight oracle
#

Okie dokie, lettme check

#

It worked :D

#

Thanks dude!

drifting arrow
#
async def autocomplete(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
        choices = []
        for item in self.items_list:
            choices.append(self.items_list[item]['name'])
        if current:
            return [
                app_commands.Choice(name=choice, value=choice)
                for choice in choices if current.lower() in choice.lower()
            ]
        else:
            default = choices[:25]
            return [app_commands.Choice(name=d, value=d) for d in default]
        
    async def autocomplete2(self, interaction: discord.Interaction, current: str) -> List[app_commands.Choice[str]]:
        serverchoices = []
        for server in self.sillyservers:
            serverchoices.append(server)
        if current:
            return [
                app_commands.Choice(name=choice, value=choice)
                for choice in serverchoices if current.lower() in choice.lower()
            ]
        else:
            default = serverchoices[:1]
            return [app_commands.Choice(name=d, value=d) for d in default]

    @ app_commands.command(name="vendingsearch", description="Searches The Rust Server's Vending Machine")
    @ app_commands.guild_only()
    @ app_commands.describe(item="List of items")
    @ app_commands.describe(server="Select a server")
    #@ app_commands.choices(server=[*server_names])
    @app_commands.autocomplete(item=autocomplete)
    @app_commands.autocomplete(server=autocomplete2)
    async def search(self, interaction: discord.Interaction, server: str, item: str):

I'm trying to get the "autocomplete" function to work for both "server" and "item" however it doesn't seem to work this way.

When I disable it for server the item autocomplete function works and vice versa.
How can I get it to work for both?

vocal snow
#

!d discord.app_commands.autocomplete

unkempt canyonBOT
#

@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.

Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.11)"), or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.11)") values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.

For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete "discord.app_commands.Command.autocomplete") documentation.

Warning

The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
vocal snow
#

You only need the decorator once, and pass two kwargs to it

winter token
#
 @commands.command()
    async def lb(self, ctx):

        gid = str(ctx.guild.id)
        if gid not in data1 or data1[gid]['lvl_mode'] != 1: # Checks if ranking system is enabled or not
            await ctx.reply("Ranking system is disabled in this guild.")
        else:
            lb = []
            for member in ctx.guild.members:
                if member.bot:
                    continue
                else:

                    id = str(member.id)
                    xp = data1[gid][id]['xp']
                    lb.append((member, xp))
            
            lb = lb.sort(key = lambda x:x[1], reverse = True)
            embed = discord.Embed(title ='Leaderboard')

            for index, (member, score) in enumerate(lb, start = 1):
                embed.add_field(name = f'{index}.', value = f'{member.mention} - XP: {score}', inline = False)
#

Error occured: Command raised an exception: TypeError: 'NoneType' object is not iterable

#

why am i getting this all the tim

obtuse nimbus
winter token
#

wont throw any error but wont response either

#

wait nvm

#

im dumb

#

forgot to add ctx.send

drifting arrow
vocal snow
drifting arrow
#

Yes

drifting arrow
vocal snow
#

full traceback please

#

can you show your file hierarchy?

slate swan
#

screenshot of file tree structure

#

of your project

#

and the code you run is inside main.py?

vocal snow
#

why is your main.py in a folder called venv

slate swan
#

it was looking for folder cogs inside venv folder either put the main.py file outside or change the path it should look for

winter token
#
 @commands.Cog.listener()
    async def on_member_join(self, member):

        gid = str(member.guild.id)
        with open('logs_data.json', 'r') as f:
            data2 = json.load(f)
        roles = data2[gid]['role']
        autorole = discord.utils.get(member.guild.roles,  name = f"{roles}")
        await member.add_roles(autorole)
#

Traceback (most recent call last):
thon311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "_logs.py", line 161, in on_member_join
await member.add_roles(autorole)
File "C\Lib\site-packages\discord\member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'

slate swan
#

looks like autorole is None

winter token
#

oh mb

#

i forgot to reset data file

#

yea worked

slate swan
#

does the cog get loaded?

#

show how you defined the commnad?>

#

and where is this command located?

#

inside cog class?

#

show full cog

#

code

#

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

slate swan
#

and how do you know the cog is being loaded

#

put a print inside constructor

#

cog constructor

#

__init__

#

just print something so we know its being invoked

upbeat gust
#

Is that the print you put in the cog __init__?

slate swan
#

ok but did it print whatever you made it to in the cog constructor

upbeat gust
#

sorry what?

slate swan
#

you are supposed to put a simple print inside the __init__ thats all

#

inside the __init__ method of the Cog

upbeat gust
#

And..? What happens

slate swan
#

does the print is being printed when you run the bot ..

#

so the cog is not loaded

#

show how you load the cogs

#

show file structure

upbeat gust
#

Wdym new mistake? What did you change?

slate swan
#

show this listener

#

why would you put __init__ inside the Cog.listener()

#

yes, why would you put it in here

#

"i changed nothing"

upbeat gust
#

do you know what __init__ is?

#

then why did you put it the decorator params??

#

I cant even comprehend that

#

what do you think it is?

slate swan
#

not like construcor is the same name for __init__

upbeat gust
#

..do you know what that means? cause you obviously didnt write that

slate swan
#

code

#
        if self.arg == "":
            title = "Набор игроков"
``` what if this if will be False
#

then the title varriable will never be created

ember mango
#

Hi,
Can anyone help me?

slate swan
#

nope since you are doing a nuke bot

ember mango
thin raft
slate swan
ember mango
turbid condor
wide kindle
#

so many nuke bots online yet you come here to make one for yourself

slate swan
thin raft
#

!d discord.Message.delete

unkempt canyonBOT
#

await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
thin raft
#

wait they changed the sintax

#

wasn't it delete_after?

turbid condor
slate swan
#

delete_after was when you were sending it

ember mango
thin raft
#

!d discord.TextChannel.send

slate swan
#

!d discord.ext.commands.Context.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
thin raft
#

yup

#

nonce?

ember mango
#

?

turbid condor
#

yeah use the delete_after and type in after how many seconds you want it to delete

slate swan
ember mango
thin raft
ember mango
#

Why Error

thin raft
#

what does this mean

ember mango
#

Anyway

slate swan
#

!d discord.Message.nonce

unkempt canyonBOT
#

The value used by the discord guild and the client to verify that the message is successfully sent. This is not stored long term within Discord’s servers and is only used ephemerally.

slate swan
#

thats like your own id for the message

turbid condor
thin raft
#

and one last question

turbid condor
upbeat gust
thin raft
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
ember mango
thin raft
upbeat gust
thin raft
upbeat gust
thin raft
#

is this done automatically?

upbeat gust
ember mango
turbid condor
slate swan
# thin raft

tried changing the type once and saw no difference

fluid dagger
#

Hello I need help I'm a beginner in python, and I'm creating a custom rp system with discord (pypresence). And I made a GUI for the question form. However if the person doesn't put an answer in an entry the code crashes I would like that a person can help me so that pypresence passes if there is not give.

Code of recuperation of data :

    id=id_entry.get()
    details=details_entry.get()
    state=state_entry.get()
    party=party_entry.get()
    min_party=min_entry.get()
    max_party=max_entry.get()
    large_img=large_entry.get()
    largetext_img=largetext_entry.get()
    small_img=small_entry.get()
    smalltext=smalltext_entry.get()
    button1_label=button1_entry.get()
    button1_url=button1_url_entry.get()
    button2_label=button2_entry.get()
    button2_url=button2_url_entry.get()
upbeat gust
fluid dagger
upbeat gust
slate swan
ember mango
#

How to remove this response 🗿

slate swan
#

you are asking how to add buttons to view?

#

here is how to create a confirm button

#

example

turbid condor
ember mango
turbid condor
silk rune
#

Wow wonderful song

turbid condor
# ember mango

instead of doing await ctx.channel.send do await ctx.send

ember mango
turbid condor
#

wdym not display slash_command

ember mango
#

Not this

#

You can make him write something instead

turbid condor
#

then just send ephemeral to true so that only the person who used the command can see the message

ember mango
#

You can do that instead
Write this and I'll write something myself

turbid condor
#

nextcord

upbeat gust
#

mb didnt check

turbid condor
#

same as delete_after

#

just put ephemeral=True

#

that should solve it

ember mango
turbid condor
#

i already told you what to do

#

shouldn't be that hard to put ephemeral in there

upbeat gust
#

it would be a diferent ctx method tho

#

reply or respond or smth

slate swan
#

its not context tho

upbeat gust
ember mango
#

Fixed Right?

slate swan
#

its not pycord as well

turbid condor
upbeat gust
#

skull

slate swan
#

nor nextcord

upbeat gust
#

nah disnake

slate swan
#

its disnake and its GuildInteraction

ember mango
turbid condor
ember mango
#

How to this work?

upbeat gust
slate swan
#

reading the docs would be a great idea

turbid condor
#

same as the prev one i guess

slate swan
#

yes read the docs

#

and see what you have wrong

upbeat gust
#

it would be just await channel.send(...)

slate swan
#

the channel will be None always

upbeat gust
#

ffs

#

how do you even end up with this many wrong things

turbid condor
ember mango
upbeat gust
#

that is not what you said

ember mango
#

Like this
Example
Who uses my command

Send channel private just code send me

upbeat gust
#

I can not comprehend what you're saying

slate swan
turbid condor
#

hint u need to put ID as an int

slate swan
#

thats what i understand as private channel

ember mango
#

Waite

#

This is how it works ?

upbeat gust
#

No

ember mango
upbeat gust
#

those guys already told you multiple times what's wrong

slate swan
ember mango
slate swan
#

no i mean read the docs

upbeat gust
ember mango
upbeat gust
#

what part is confusing?

ember mango
turbid condor
#

the current problem you have is with the data type

slate swan
upbeat gust
#

that's just random words

ember mango
#

Waite

upbeat gust
#

If english isnt your first language, try google translate?

upbeat gust
#

bro you've sent that 3 times now

slate swan
#

sending the same screenshot over and over isnt going to explain it

upbeat gust
#

we've already told you the things you need to fix

ember mango
#

Whenever they use it, I want you to send the bot to that channel

upbeat gust
#

okay? and??

#

we've told you multiple times what to fix

ember mango
naive briar
#

Great ducky_wizard

slate swan
ember mango
#

Man i mean Like logs whenever you use them send them to that channel

turbid condor
turbid condor
slate swan
#

did you check the example i sent?

ember mango
slate swan
ember mango
slate swan
ember mango
#

I don't understand docs

#

Can you help me?

upbeat gust
#

we did 💀

slate swan
#

what you dont understand in it

upbeat gust
#

looks like youve ignored all of it

ember mango
#

I finally fixed it thanks for your help.
@slate swan @turbid condor

slate swan
#

try it out and see how it works

#

then try to implement it in your case

#

then go to disnake github

#

they have examples as well

young dagger
#

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

slate swan
#

the token you passed was None

sharp whale
#

can anyone assist me with lavalink

slate swan
#

looks like os.getenv returned None

#

!d os.getenv

unkempt canyonBOT
#

os.getenv(key, default=None)```
Return the value of the environment variable *key* as a string if it exists, or *default* if it doesn’t. *key* is a string. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.

On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.

[Availability](https://docs.python.org/3/library/intro.html#availability): Unix, Windows.
slate swan
#

do you load the environment varriavles?

#

show code

#

you have the token in the .env file?

sharp whale
slate swan
sharp whale
#

D:

young dagger
#

How can I disable a discord.ui.button after 60 seconds?

#

I'm not looking for timeout, but actually to disable it

slate swan
#

set timeout to 60s and disable it out timeout

#

!d discord.ui.View.on_timeout

unkempt canyonBOT
#

await on_timeout()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A callback that is called when a view’s timeout elapses without being explicitly stopped.
slate swan
#

so where you have it

young dagger
#

Ignore if self.vote_count >= 1: it's just for testing

slate swan
#

then you override on_timeout method and disable the button in this method

upbeat gust
#

elaborate on "doesnt work"

slate swan
young dagger
slate swan
#

ah yes you did not pass message

#

do like this in your command

view = Counter()
view.message = .send(..., view=view)
young dagger
#

Thanks Down

lofty pecan
#

Hey there, when using commands.hybrid_command() how can I check user has admin perms?

slate swan
#

either commands.has_permissions or app_commands.checks.has_permissions

#

not sure which one though

#

one of those

lofty pecan
#

this is weird

#

because I've made slash commands, they all work

#

but then I do the same in my admin.py file

#

but I get an error message

slate swan
#

show the error maybe

lofty pecan
#

Error when logging in: Extension 'cogs.admin' raised an error: TypeError: unsupported parameter kind in callback: VAR_POSITIONAL

#

yeah sorry I was copying it ^^

slate swan
#

show code

#

!paste if too long

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.

lofty pecan
#

ho hold on then

slate swan
#

you misspelled the permission

#

manage_rolesis

turbid condor
lofty pecan
#

Still get the error though

slate swan
turbid condor
#

Just make it roles

lofty pecan
#

yeah but isn't it a problem if it's not *roles?

turbid condor
#

That should work

#

Let me check haven't checked your code

lofty pecan
#

Error when logging in: Extension 'cogs.admin' raised an error: TypeError: unsupported parameter kind in callback: VAR_POSITIONAL

#

hehe ... it doesnt

#

ho wait

#

pff I changed the wrong one

#

now it works lmao

slate swan
#

you have that in two commands

lofty pecan
#

thanks !!

slate swan
#

what doesnt work mean

#

still dont understand what does not work

turbid condor
#

I think his persistent view is not working when he runs it from main.py but when he runs it from confirm.py they work

#

Tho idk the full story since wasn't involved in the problem solving

slate swan
#

what are confirm.py and main.py

left dew
#

is it possible to restrict one select value in a drop-down menu to a user with a particular role?

gaunt flare
#

how tf do i define guild

chrome veldt
#

how to i get the top to read it all as one argument

tawdry nimbus
chrome veldt
#

current code

tawdry nimbus
chrome veldt
#

ok ill try that

turbid condor
mossy moth
#

Hello all. I understand bots do not have access to user's connections, and instead one would need to use OAuth2 and a web application. Would passing the response back to the bot program be against TOS, or, more importantly, would Discord be able to detect this behavior? Already got my account blocked for too many logins with Selenium

left dew
#

how can i check whether there are numbers in a message content?

left nova
#

hi i need help with my telegram bot code... anyone know a server where you can help each other?

sick birch
mossy moth
turbid condor
tawdry nimbus
#

you can use the users api endpoint

mossy moth
#

Just trying to get users connected Steam account user ID so I can use for Steam API. It's been a massive headache so I'm open to any suggestions if there's an easier way to do it than OAuth

tawdry nimbus
#

it returns a lot of info

tawdry nimbus
#

ill show u an example wait

mossy moth
left dew
tawdry nimbus
#

you do need a user account token in the authorization headers tho

#

could use yours

#

or an alt's

unkempt canyonBOT
#

5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

mossy moth
tawdry nimbus
#

?

#

how is that against tos

mossy moth
#

Beats me, but I'll separate the API call from the bot code to keep it legal lol. Thanks again

slate swan
tawdry nimbus
slate swan
#

thats exactly what self bot is

left dew
slate swan
#

like ```py
def extract_numbers(string):
return "".join(filter(str.isdigit, string))

left dew
#

uhhh

naive briar
#

Regex ducky_wizard

slate swan
left dew
#

im just wanting to store the number that a user puts in their message e.g. 100 crates, it will store the 100

slate swan
#

!e ```py
def extract_numbers(string):
return "".join(filter(str.isdigit, string))

print(extract_numbers("abc123def456"))

unkempt canyonBOT
#

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

123456
naive briar
left dew
#

ohhh thanks

slate swan
# naive briar What

i would have to say that he needs to import additional module and what it is blahblahblah

naive briar
#

I'm just saying that they can also use regex, but fair, I guess

left dew
# slate swan i would have to say that he needs to import additional module and what it is <a:...

so im making like a game bot and they can order a purchase with their coins and get crates and stuff, so in a modal ive made it so they can input their order with x20 crate1, x40 crate3, x70 crate3 etc. now i get these values by splitting this order and using the order[0]. however, the order length wont be the same for everyone and so i have to make the order length the same for now. how would i make it so the orderlength can be different and so i can split it and get each part of the order?

vocal snow
#

no

gloomy hound
#

I was wondering, is there a way to reduce this code by putting the decorator method (with the "@") into the class block ?

import discord
from discord.ext import commands

class Bot(commands.Bot):
  pass

bot = Bot(...)

@bot.tree.command(name="hi", description="Greets the bot !")
async def greet(interaction: discord.Interaction):
    await interaction.response.send_message("Hi there !")
#

something like

import discord
from discord.ext import commands

class Bot(commands.Bot):
  @Bot.tree.command(name="hi", description="Greets the bot !")
  async def greet(interaction: discord.Interaction):
    await interaction.response.send_message("Hi there !")
potent spear
potent spear
gloomy hound
gloomy hound
potent spear
gloomy hound
#

I meant class methods mb

fiery jetty
slate swan
formal basin
#
ValueError: I/O operation on closed file.```
how do I open a file
#

txt

formal basin
# slate swan show code
counter = 0
     with open("/home/container/spam.txt", "r+") as file:
      for lines in file:
       if lines.strip("\n") == str(message.author.id):
         counter+=1
    
     file.writelines(f"{str(message.author.id)}\n")
     if counter == 5:```
slate swan
formal basin
#

instead of with open

slate swan
#

Just put it inside with block

formal basin
slate swan
#

i think you are not getting the point how the with works

formal basin
#
     curr_time = datetime.datetime.now().timestamp() * 1000

     if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

     author_msg_times[author_id].append(curr_time)

     expr_time = curr_time - time_window_milliseconds

     expired_msgs = [msg_time for msg_time in author_msg_times[author_id] if msg_time < expr_time]

     for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)

     if len(author_msg_times[author_id]) == max_msg_per_window:
        try:
            key3 = f'antispam:{message.guild.id}'
            if r.exists(key3):
             minutes = r.get(key3)
             min = int(minutes.decode("utf-8"))
             duration = datetime.timedelta(minutes=min)
             await message.author.timeout(duration)
             embed = discord.Embed(title="User Muted", description=f"{message.author.mention} has been muted", color=discord.Color.blue())
             print(f"spam detected: {message.guild.id}")
             embed.add_field(name="Reason", value="Spamming")
             embed.add_field(name="Mute Duration", value=f"{min} minutes")
             await message.channel.send(f"{message.author.mention} no spamming allowed")
             log = r.get(f"logs:{str(message.guild.id)}")
             log2 = int(log.decode("utf-8"))
             logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
             await logging_channel.send(embed=embed)
             print(f"spam detected logs: {message.guild.id}")
            else:
              pass
        except KeyError:
            pass
           ``` i have an anti spam thing
#

but its slow

#

should my on_message be under all the commands?

potent spear
fickle crown
#

await first_channel_message.reply(content=None, components=[first_channel_give_button, first_channel_remove_button])
TypeError: Messageable.send() got an unexpected keyword argument 'components'

potent spear
cobalt latch
#

nvm i am a big idiot

snow coral
#

this isnt blocking when a blacklisted word is showing

    'u coders dont gotta see this'
    'u coders dont gotta see this'
    'u coders dont gotta see this'
    'u coders dont gotta see this'
    'u coders dont gotta see this'
    'u coders dont gotta see this'
    'u coders dont gotta see this'
    'u coders dont gotta see this'
]

@bot.command()
async def love(ctx, name1, name2):
    love_percentage = calculate_love_percentage(name1, name2)
    if name1 == blacklistedwords and name2 == blacklistedwords:
        ctx.send('try something more appropriate please.')
    else:
        await ctx.send(f'The love percentage between {name1} and {name2} is {love_percentage}%.')
def calculate_love_percentage(name1, name2):
    random.seed(name1.lower() + name2.lower())
    love_percentage = random.randint(0, 100)
    return love_percentage```
potent spear
snow coral
#

if

#

name 1 has blacklisted words

potent spear
#

incorrect

snow coral
#

o

potent spear
#

it's not has it's IS

#

so your word will never be equal to a list

snow coral
#

oooooh

potent spear
#

so instead, you need in

#

!e

a_list = ["a", "b", "d"]

if "a" == a_list:
  print("oeuf")

if "d" in a_list:
  print("we're in boys")```
unkempt canyonBOT
#

@potent spear :white_check_mark: Your 3.11 eval job has completed with return code 0.

we're in boys
snow coral
#

thanks

lethal drift
#

What's the correct way to defer a slash command?

naive briar
#

!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...
naive briar
#

Defer it before doing anything that will take a long time to complete

lethal drift
#

So would it be interaction.defer() or interaction.response.defer()?

naive briar
#

The second one

lethal drift
#

No wonder it wasn't working, thank you

formal basin
#
author_id = message.author.id
     curr_time = datetime.datetime.now().timestamp() * 1000

     if not author_msg_times.get(author_id, False):
        author_msg_times[author_id] = []

     author_msg_times[author_id].append(curr_time)

     expr_time = curr_time - time_window_milliseconds

     expired_msgs = [msg_time for msg_time in author_msg_times[author_id] if msg_time < expr_time]

     for msg_time in expired_msgs:
        author_msg_times[author_id].remove(msg_time)

     if len(author_msg_times[author_id]) == max_msg_per_window:
        try:
            key3 = f'antispam:{message.guild.id}'
            if r.exists(key3):
             minutes = r.get(key3)
             min = int(minutes.decode("utf-8"))
             duration = datetime.timedelta(minutes=min)
             await message.author.timeout(duration)
             embed = discord.Embed(title="User Muted", description=f"{message.author.mention} has been muted", color=discord.Color.blue())
             print(f"spam detected: {message.guild.id}")
             embed.add_field(name="Reason", value="Spamming")
             embed.add_field(name="Mute Duration", value=f"{min} minutes")
             await message.channel.send(f"{message.author.mention} no spamming allowed")
             log = r.get(f"logs:{str(message.guild.id)}")
             log2 = int(log.decode("utf-8"))
             logging_channel = client.get_channel(log2) or await client.fetch_channel(log2)
             await logging_channel.send(embed=embed)
             print(f"spam detected logs: {message.guild.id}")
        except KeyError:
            pass

this code is delayed then spams the logging_channel.send and the message.channel.send and then it gets like rate limited

#

it was working fine

#

then stopped working

#

well delayed

#

or maybe my network

midnight oracle
#

What's the correct way of importing a Cog command/s to the main file? Because I get a "The command <command_name> does not exist.

maiden fable
unkempt canyonBOT
#

await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.11)").
midnight oracle
#

srry, beginner in Discord bots :v

turbid condor
midnight oracle
lethal drift
#

@slate swan you need to ask here and not in dms

turbid condor
ember mango
#

Hello Can Anyone Help me?

lethal drift
#

You need to be more specific, what is happening? and show errors

vocal snow
lethal drift
ember mango
vocal snow
#

and you can probably shorten that code a whole lot if you use appropriate data structures

ember mango
#

I have defined that

lethal drift
vocal snow
#

christ

lethal drift
#

That's the only way you'd have it defined

#

also so many elif's-

ember mango
vocal snow
#

you really should learn how to use lists and loops

lethal drift
vocal snow
#

hardcoding everything is not a good solution

ember mango
vocal snow
#

can you share your code?

slate swan
#

omg zeffo

#

Hi!!!

vocal snow
#

the relevant parts in both

#

if it's too long you can use !paste

slate swan
#

I am not fembou

ember mango
lethal drift
vocal snow
#

can you share the full trace?

ember mango
vocal snow
#

i see

slate swan
vocal snow
#

can you share the extension code?

ember mango
ember mango
slate swan
#

You are defining variables inside conditional statements

ember mango
ember mango
vocal snow
#

yea, can you share the code for cogs.confirm

slate swan
vocal snow
#

your code is trying to load cogs.confirm though

lethal drift
# ember mango Check phto

also if no matter the random outcome, they're gonna be defined the same, what's the point of the conditionals?

slate swan
#

Zeffo how to solve typeerror in my bot

vocal snow
slate swan
#

Oh ok thanks

lethal drift
#

oop 🤣

slate swan
vocal snow
#

sure

slate swan
#

is confirm an extension

vocal snow
#

It has a setup function right?

slate swan
#

If it only contains classes and you wanna put it as file in cogs then no

vocal snow
#

show the setup function code

naive briar
#

Show the Confirm class' code

#

Or just its __init__

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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

naive briar
#

It isn't a cog

vocal snow
#

this is a View not a Cog

#

what are you trying to do exactly

#

yes, but why is it in an extension

#

which part of your code uses that view

#

so why not just define the view there

#

in the same file which uses it

slate swan
#

By copy pasting that code in the "modal" you are talking about

#

In the file you are using that class

#

Where are you exactly calling that class, like where are you using it

#

You must be creating an object of it somewhere

#

yes Confirm class

#

You have created a View

#

So you are supposed to use it right

#

You use it by calling the class, like so

view = Confirm()

And pass it in .send(msg, view=view)

#

If you want to do it in a command then
Eg

@bot.command
async def example(ctx):
    view = Confirm()
    await ctx.send(somemsg, view=view)
ember mango
#

Hello, Anyway Know My bot Just Dm work Why I can't Use Commands In channel But I can Use on dm why?

slate swan
#

Confirm should either be imported or copy pasted in that same file

#

Yes

#

Is it working now

naive briar
naive briar
#

What?

slate swan
#

Any error

#

Is that command working

ember mango
naive briar
#

Where is the Confirm class from

#

Because it doesn't seem like that code is in the same file as the class

naive briar
#

What??

ember mango
naive briar
#

What does that mean

naive briar
ember mango
slate swan
#

Is there any error

ember mango
naive briar
slate swan
#

The command's name is ask not confirm

ember mango
naive briar
#

Show your entire code

ember mango
#

Anyone HELP ME??

naive briar
#

The error literally just told you how to solve itself, read it

naive briar
slate swan
#

The file in which you are creating the bot

#

Main file

ember mango
slate swan
#

Where is that ask command

ember mango
#

Fixed Ty

slate swan
#

Where is the ask command

#

did you put it in that confirm file

#

Why are you creating two different bots

#

Copy the Confirm class and ask function and paste them in this file ^

#

Also import the necessary modules

ember mango
#

Anyone Know Guild Prefix?

#

RIGHT: async def hi (ctx: guild)

ember mango
slate swan
#

Show what you did

turbid condor
#

as for prefix u want to change it?

slate swan
#

Yeah, show

ember mango
turbid condor
#

You mean that u want a command to not be used in dm?

#

Just in server

slate swan
#

Hmmm so what happens when you try to run commands present in cogs

#

So it's working now?

turbid condor
# ember mango Yes

There should be a check called guild_only() use that for commands tha you want to be used in guilds only

slate swan
#

Let's gooo

ember mango
turbid condor
#

Welp idk about nextcord like how to use checks in that if it's same as dpy then

@bot.command()
@commands.guild_only()
async def hi(ctx):
#

That's how u do it in discord.py but don't know if it works for nextcord

vocal laurel
vocal laurel
#

@app_commands.guild_only?

ember mango
#

Note i use disnake

vocal laurel
vocal laurel
naive briar
#

!d discord.app_commands.guild_only

unkempt canyonBOT
#

@discord.app_commands.guild_only(func=None)```
A decorator that indicates this command can only be used in a guild context.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"), and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.

This decorator can be called with or without parentheses.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.

Examples...
turbid condor
#

@app_commands.checks.guild_only() or @checks.guild_only()

ember mango
turbid condor
#

dm_only

vocal laurel
#

?

naive briar
#

There's no such thing

#

Just make your own check

vocal laurel
turbid condor
#

U sure u tried dm_only()?

vocal laurel
#

so it isnt in the docs but it exists?

#

or i might of typed it wrong idk

naive briar
#

It doesn't exist

vocal laurel
turbid condor
#

Then it might be for prefix commands only then

#

Yup it is for prefix commands only

slate swan
#

!d nextcord.ext.commands.Bot.slash_command

unkempt canyonBOT
#

slash_command(name=None, description=None, *, name_localizations=None, description_localizations=None, guild_ids=..., dm_permission=None, nsfw=False, default_member_permissions=None, force_global=False)```
Creates a Slash application command from the decorated function.
slate swan
#

!d nextcord.Locale

unkempt canyonBOT
vocal laurel
#

well u want buttons under a message right?

slate swan
#

!d nextcord.ext.application_checks.check_any

unkempt canyonBOT
#

@nextcord.ext.application_checks.check_any(*checks)```
A [`check()`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.check "nextcord.ext.application_checks.check") that will pass if any of the given checks pass, i.e. using logical OR.

If all checks fail then [`ApplicationCheckAnyFailure`](https://nextcord.readthedocs.io/en/latest/ext/application_checks/index.html#nextcord.ext.application_checks.ApplicationCheckAnyFailure "nextcord.ext.application_checks.ApplicationCheckAnyFailure") is raised to signal the failure. It inherits from [`ApplicationCheckFailure`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.ApplicationCheckFailure "nextcord.ApplicationCheckFailure").

Note

The `predicate` attribute for this function **is** a coroutine.
slate swan
#

no its for me

turbid condor
#

have u created the button logic?

primal pike
#

!d status

unkempt canyonBOT
#

Rich can display a status message with a ‘spinner’ animation that won’t interfere with regular console output. Run the following command for a demo of this feature:

python -m rich.status
```  To display a status message, call [`status()`](https://rich.readthedocs.io/en/stable/reference/console.html#rich.console.Console.status "rich.console.Console.status") with the status message (which may be a string, Text, or other renderable). The result is a context manager which starts and stops the status display around a block of code. Here’s an example:

```py
with console.status("Working..."):
    do_work()
```  You can change the spinner animation via the `spinner` parameter...
young dagger
#

What is wrong?
Unresolved attribute reference 'message' for class 'Counter'
Unresolved attribute reference 'message' for class 'Counter'
Cannot find reference 'edit_message' in '() -> InteractionResponse'
Cannot find reference 'send_message' in '() -> InteractionResponse'
Cannot find reference 'send_message' in '() -> InteractionResponse'


await interaction.response.edit_message(view=self)
await interaction.response.send_message("You can only vote once.", ephemeral=True)
await interaction.response.send_message("You are not eligible to vote.", ephemeral=True)

            await self.message.edit(content=None, embed=embed, view=self)
            await self.message.edit(view=self)

    view = Counter()
    view.message = await ctx.send(embed=embed, view=view)```
young dagger
#

Yes

thin raft
#

ignore

#

It also happens to me

#

couldn't find a fix

young dagger
thin raft
young dagger
#

Cannot find reference 'send_message' in '() -> InteractionResponse'

await interaction.response.send_message("You can only vote once.", ephemeral=True)

young dagger
vocal laurel
#

Any errors??

young dagger
#

There is no traceback errors

slate swan
#

so whats the problem

young dagger
#

The warning messages?

slate swan
#

if the code is running it means it works

#

and as you said they are warnings not errors

#

try different ide

pulsar pine
#

Looking for dev that can make a discord bot for me dm me for more info if you are interested

left stirrup
#

Can somebody explain this:

class JoinDistance:
    def __init__(self, joined, created):
        self.joined = joined
        self.created = created

    @classmethod
    async def convert(cls, ctx, argument):
        member = await commands.MemberConverter().convert(ctx, argument)
        return cls(member.joined_at, member.created_at)

    @property
    def delta(self):
        return self.joined - self.created

@bot.command()
async def delta(ctx, *, member: JoinDistance):
    is_new = member.delta.days < 100
    if is_new:
        await ctx.send("Hey you're pretty new!")
    else:
        await ctx.send("Hm you're not so new."```
#

how is the classmethod ran if I never called it

slate swan
left stirrup
#

oh so it gets called automatically

slate swan
#

YES

#

caps

#

more explained here

left stirrup
#

ty

#

Wait do I need to add a converter for ctx? py ctx: commands.Context

slate swan
#

what you mean by that?

left stirrup
#

i mean the commands.Context

slate swan
#

thats just annotation

#

no need to add it

left stirrup
#

oh okay

turbid condor
#

not needed by default the first is arg is Context

left stirrup
#

whats the difference between a member and a user?

slate swan
#

Member is for a desired guild

#

User is all discord

left stirrup
#

ty

swift acorn
#
# This is the button class of xboxreactbutton
class xboxreactbutton(View):
    def __init__(self):
        super().__init__(timeout=None)
        
    @button(label="Xbox", style=discord.ButtonStyle.green, custom_id="1", emoji="![StumbleXbox](https://cdn.discordapp.com/emojis/1128685955960815767.webp?size=128 "StumbleXbox")")
    async def submitbutton(self, interaction: discord.Interaction, button: Button):
        await interaction.response.defer(ephemeral=True)
        xbox_role = interaction.guild.get_role(1128348625785847940)
        if xbox_role in interaction.user.roles:
            await interaction.user.remove_roles(xbox_role)
            await interaction.followup.send(f"Added {xbox_role.mention} role!", ephemeral=True)
            return
        await interaction.user.add_roles(xbox_role)
        await interaction.followup.send(f"Removed {xbox_role.mention} role!", ephemeral=True)


# This is inside the command that sends the embed
    view = xboxreactbutton()
    view.add_item(discord.ui.Button(label="Pre Register", url="link/register"))
    await interaction.channel.send(embed=embed, view=xboxreactbutton())

Hey, this is working but it is not showing the url button, only the xbox one, any idea why?

naive briar
#

Because I believe it needs to be

swift acorn
#

It works now

naive briar
#

Didn't notice that

young dagger
#

How do I prevent the button from delaying timeout after each interaction?

#

super().__init__(timeout=60)

#

But every time the button is clicked, it resets the timeout

formal basin
#

i think its because i have so many listen events for on_message

shrewd apex
formal basin
#

!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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

formal basin
slate swan
formal basin
#

wait if i put 1 on top it will still ignore itself?

slate swan
#

yes?

formal basin
#

oh

slate swan
formal basin
slate swan
#

this code is so messy i dont know

formal basin
#

only the first few lines work

slate swan
#

maybe cause you have so many if else that doesnt make sense

formal basin
#

oh

#

I deleted the the else that I dont need but still not doing anything

#

anyone else know?

turbid condor
#

Tbh instead of so many if statements can't u use elif?

#

And then again your code is too messy can't understand what u are trying to do or achieve

slate swan
#

also many of lines look like they repeat or have almost the same logic

turbid condor
#

I'll suggest him seperating this event into multiple functions or cogs

rustic onyx
slate swan
unkempt canyonBOT
rustic onyx
#

is there any open source code example to know when a youtube channel uploaded a video?

#

for comparison, what mee6 does for example

slate swan
#

How can i send a File using Discords API?

formal basin
#

its an anti spam
but its like 10 seconds delayed
then after the 10 seconds it spams message.channel.send and logging_channel.send

ember mango
#

Hello, Anyway Know How to Just One Rile Can Use slash command?

ember mango
#

@sick birch

snow coral
#

how can i make my bot watch over the chat and have something happen if someone says a certain word

sick birch
#

I believe that restricts only the people you've selected to be able to see it

rustic onyx
#

!pypi fastapi

unkempt canyonBOT
#

FastAPI framework, high performance, easy to learn, fast to code, ready for production

sick birch
ember mango
#

But i mean code

sick birch
#

pithink I mean okay I guess

sick birch
#

The first example has pretty much exactly what you want

sick birch
#

Same concept

slate swan
#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
sick birch
#

There you go

ember mango
sick birch
#

Yes

slate swan
ember mango
#

Right??

slate swan
#

no its a decorator

#

you put it above the function

upbeat otter
#
@decorator
def function():
  ...

that's the flow

chrome veldt
#

my bot is going well but i need to be able to have either a file or string as a argument but i dont know how to do such a thing

upbeat otter
chrome veldt
#

yeh but i want to do either

#

for the same command

slate swan
#

discord.Attachment | str

#

might work

upbeat otter
#
# if python 3.10 or higher
argument: str | discord.Attachment

# or

from typing import Union

argument: Union[str, discord.Attachment]
chrome veldt
#
async def stats(ctx: commands.Context, blueprint : discord.Attachment | str):

?

upbeat otter
#

"might work"

#

yes

chrome veldt
#

now

#

now i gotta figure out how discord read it

#

didnt workj

#

said the argument was missing

slate swan
chrome veldt
slate swan
#

and what was the error you got?

chrome veldt
#

discord.ext.commands.errors.MissingRequiredArgument: blueprint is a required argument that is missing.

slate swan
#

hm well looks like you cant mix it up

chrome veldt
#

hmm

#

well ig i can have !statstext and !statsfile

slate swan
#

either create 2 commands one for file and one for text or accept only files/text or try playing with converters

chrome veldt
#

but duplicated code but ohwell

slate swan
chrome veldt
#

me#

slate swan
#

create function to handle input

#

and just call it in two commands

chrome veldt
#

now how to convert discord attachment to longgggg string

slate swan
#

!d discord.Attachment

unkempt canyonBOT
#

class discord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
slate swan
#

!d discord.Attachment.read

unkempt canyonBOT
#

await read(*, use_cached=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.

New in version 1.1.
chrome veldt
#

like this ?

slate swan
#

no

chrome veldt
#

oh