#discord-bots

1 messages · Page 372 of 1

hearty basalt
#

seeing as he's defining vouches as a dictionary

#

im only sayin from experience, ive never used a database before lol

fast osprey
#

You should not use just a json file

#

Unless you're keen on poor performance and having your data randomly corrupted

hearty basalt
#

ite

#

ty for explaining

quick gust
#

just use a file based database if u dont wanna put that much effort

fast osprey
#

sqlite is super fast to spin up and use if you know sql basics

quick gust
#

yeah no credentials stuff

#

I like to use it for small scale bots

fast osprey
#

SQLite scales incredibly well, it's less about scale and more about whether or not you need a server client model

timber dragon
quick gust
fast osprey
#

Not sure what you mean by "file based", or what you think is going on under the hood with things like Postgres

#

(Files)

quick gust
#

.db files

fast osprey
wet talon
#

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

wet talon
upbeat otter
#

and what's the error or where does the code stop running

wet talon
#

when the user clicks incorrect, the bot deletes the messages but does not resend the deal amount request

upbeat otter
wet talon
#

yes

fast osprey
slate crest
#

right thank you love you, havent done this in a long time

slate crest
fast osprey
#

I would recommend using a listener instead for simplicity

#

You should only need to override and run process_commands if there are cases where you don't want to process commands

solid pecan
#

yo guys i have a small question

#

how can i get the message from discord api

#

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

#

async def kick(self, ctx, message: discord.message):

#

for some reason it doesnt allow me to use the message content

shrewd apex
#

u need channel id and message id both

#

then u can fetch the message

solid pecan
#

why does it give me it here tho

shrewd apex
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
solid pecan
#

async def on_message(self, message):

shrewd apex
#

thats an event

#

its triggered everytime u get a message

solid pecan
#

so that event has the message already included?

shrewd apex
#

ur talking about a command ur defining

fast osprey
#

Discord sends it to the bot as a part of the event payload

solid pecan
#

oh ok

solid pecan
shrewd apex
#

marks id as a positional parameter

solid pecan
#

what does that mean

shrewd apex
#

any args b4 the / are strictly positional

#

!pep 570

unkempt canyonBOT
fast osprey
#

Google is your friend here

shrewd apex
#
In [1]: def foo(a, b, /):
   ...:     return a, b
   ...:

In [2]: foo(1, 2)
Out[2]: (1, 2)

In [3]: foo(1, b=2)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 foo(1, b=2)

TypeError: foo() got some positional-only arguments passed as keyword arguments: 'b'

just means u cant pass the stuff as keyword arguments they are strictly positional

solid pecan
#

ah

#

so the only thing i can use is "id"

#

and i cant change the position

shrewd apex
#

there is also * which is responsible for keyword arguments

shrewd apex
solid pecan
#

im tryna read more about fetch message but i cant find it

solid pecan
fast osprey
#

If you want someone to pass a message in for a command, consider making a message context menu instead

quick gust
#

following up on this, could there be any work around? like maybe overriding the interaction_check method of CommandTree Or smth?

fast osprey
solid pecan
#

im basically trying to replicate a kick command but to do that i need to find the content in the message so i can know which user to kick

fast osprey
#

Why not use the built in kick command?

solid pecan
fast osprey
#

You can learn without reducing security

solid pecan
#

how am i reducing security?

quick gust
#

my only goal is to have a method which forms and sends the embed to the context location. While using prefix commands I just made a customcontext class which had a send_embed method. that way I did not have to
await ctx.send(embed=embed) (and also form the embed)
and just had to
await ctx.send_embed(text)

fast osprey
#

There's a million other things you can make besides replicating something that already exists but worse that is also bad for security

solid pecan
#

im not ever willing to publish the bot in the market..

#

im just developing discord bots to learn python

fast osprey
#

Knowing the tools you have available is a part of learning

solid pecan
#

well i'd like to know how they work

fast osprey
#

But why a kick command? You could replicate the 8000 other operations on the api that also aren't sensitive or security gated. There's a reason why people pick that specifically, and it's due to misinformation

solid pecan
#

what can i replicate?

fast osprey
#

Look at anything you do in discord

#

Almost every button or menu has an api endpoint backing it

#

From a learning perspective, kicking or banning a member is no more interesting or complex than changing their nickname or moving them between voice channels or muting them etc etc. All single api calls, it's just the former are sensitive and have very specific protections on them that you aren't going to replicate

shrewd apex
#

make some ai response command based on message context, or make some code evaluation based on a message context menu so may ways lol get creative

solid pecan
#

ok

fast osprey
shrewd apex
#

hmm it has prohibitions on like gen ai? lemme take a look

fast osprey
#

Says "do not use message content to train AI models without discord's consent", paraphrased

shrewd apex
#

but is training same as prompt generation?

#

like i actively want to generate some response out of my query as an user does that violate the tos?

fast osprey
#

Not a lawyer, but I personally wouldn't fuck with passing any user content into anything vaguely AI

#

Nor do I ever want someone doing that with my content in any capacity

shrewd apex
#

hmm fair i suppose

fast osprey
#

And if you didn't design and host the model yourself, you have no idea what it's doing when you pass a string into it

#

Going out on a limb and guessing that a vast majority of bot developers are not also professional AI scientists brewing their own models

solid pecan
fast osprey
#

mee6 also literally scams people

solid pecan
#

scams?

fast osprey
#

Not a good measuring stick to decide what's morally okay to do with your work lol

solid pecan
#

isnt that shit the most popular bot

fast osprey
#

That is not mutually exclusive with being shitty, unfortunately

#

The new policy is also not in effect yet

#

It was just announced like yesterday

solid pecan
#

oh

hearty basalt
#

i remember when they were slowly making each feature 'premium'

wanton current
#

Yeah, i'm not paying $90 to send custom embeds

hearty basalt
#

better to make your own fr

#

making embeds is hella easy too

wanton current
#

that's what im saying

#

90% of features are just meh

past plaza
#

should i make language switch for my bot?

fast osprey
#

Unlikely it's worth it unless you have a personal preference

#

Most of the major libraries have feature parity

upbeat otter
#

Hey, why is my bot not able to sync the application commands to my server

await self.load_extension("Luna.extensions.general")

if self.settings.AUTO_SYNC_APP_COMMANDS:
    synced_commands = await self.tree.sync(guild=discord.Object(self.settings.GUILD_ID))
    print(synced_commands)
    # Output: []

.I have a GroupCog in the general.py file. Also, when I log the information on startup, discord.py does recognize the general group though it does not sync.

#

I haven't use dpy in like 2 years 💀

fast osprey
#

You shouldn't ever be auto syncing

#

But check to see if your commands are also registered to the same guild

upbeat otter
wanton current
#

why not just have a command for syncing

upbeat otter
#

Can we solve the main issue here pls? 🗿

wanton current
#

If your commands are "global", and you're syncing to one guild. Only commands that have also been set to sync to that guild are synced.

upbeat otter
#

Oh shit I forgot to copy it to global 💀 alrght thanks

wanton current
#

👍

fast osprey
#

This does matter as you will quickly rate limit yourself and be unable to do anything for days

shrewd apex
#

is the rate limit that long?

wanton current
#

eventually

#

i suppose

shrewd apex
#

hmm

#

iirc gamecracks posted about the amount of times u can sync commands which is counted towards rate limits i think that happens when creating and deleting commands afaik

solid pecan
#

i do run my bot multiple times

fast osprey
#

Who knows what you're doing lol

#

That's just a very specific and strict bucket

wanton current
#

if you're syncing on start up, and then restarting your bot every time you make a change, that will get you ratelimited in the blink of an eye

solid pecan
fast osprey
#

You can get rate limited on literally any action you do that talks to the api

main holly
#

hey guys

#

so i need help

#

2024-06-08 20:40:28 ERROR discord.ui.view Ignoring exception in view <SupportView timeout=None children=1> for item <SupportDropdown placeholder='Select a support option' min_values=1 max_values=1 disabled=False options=[<SelectOption label='General Support' value='general' description=None emoji=None default=False>, <SelectOption label='High Rank Support' value='high_rank' description=None emoji=None default=False>, <SelectOption label='Management Support' value='management' description=None emoji=None default=False>]>
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "/home/container/bot.py", line 44, in callback
await self.create_support_channel(interaction, channel_name)
File "/home/container/bot.py", line 55, in create_support_channel
channel = await interaction.guild.create_text_channel(channel_name, category=self.category, overwrites=overwrites)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/guild.py", line 1369, in create_text_channel
data = await self._create_channel(
^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/guild.py", line 1227, in _create_channel
payload = {'allow': allow.value, 'deny': deny.value, 'id': target.id}
^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'

pale zenith
main holly
#

yea i still dont work

fast osprey
#

If it's the same error, you didn't fix it. If it's a different error, we'll need that.

You also should strongly consider generating threads rather than channels for this purpose.

main holly
#

i just retyped it all and it worked

vapid parcel
#

Best way to grow your discord bot or make it be seen?

versed basalt
#

My discord bot is integrated with a private Plex Server, users can look up movie titles and if it's on the server the bot will respond with an embed with information about the movie. Is there ways to get neater formatting out of this, like reduce some of the empty space?

golden portal
#

i guess if you want a smaller one just use embed description, and format them as
Title: The Room
Year: 2003
...

#

using embed fields only get you that much space

flat pier
#

alternatively just change around how you're setting up ur embed if you want it to be smaller

#

i forgot director but it gets the point across

#

but because this is a specific use case and probably only you and a few others will utilize it you can assume people know what each thing is, i.e the title and link not needing its own field and just paring it in the embeds actual title and url

versed basalt
#

that makes sense, I appreciate the suggestions

upbeat otter
cedar sail
#

Anyone here knows how to create telegram bot with python? I just want the bot to send a message when start button is pressed

mild token
quaint obsidian
#

How can I handle this rate limit? [WARNING ] discord.http: We are being rate limited. What event shoud I use?

#
@bot.event
async on_error()``` 

is not called and

@bot.event
async def on_request_error(response, data):


is not called.

There is no documentation for other error handling events that I can find in discord.py docs. I mean it is hard to find something there in general.
timber dragon
#

That's logged while doing requests

#

Nothing it called for it

#

You should check the routes it's called for and "fix" your code spamming that

pure basin
#

is there a package for instagram so whenever a specific person posts a reel it sends it in a channel through a webhook?

quaint obsidian
timber dragon
#

Aha

quaint obsidian
#

And I want when it gets timeouted to send message or to do some action.

#

I just realize that it can't do any action, because it is rate limited.

#

But still. How can I do it?

timber dragon
jade jolt
#
import discord

from discord.ext import commands

def setup(bot):
    bot.help_command = HelpCommand()


class HelpCommand(commands.HelpCommand):
    def __init__(self):
        super().__init__(command_attrs={
            'help': 'Shows help about the bot, a command, or a category'
        })
        
    def command_not_found(self, string):
        return
        
    async def send_bot_help(self, mapping):
        embed = discord.Embed(color=0xfd7aff,
                              title=self.context.bot.user.name,
                              description=f"Use `{self.context.prefix}help cog_name` to see the commands")
        
        cogs = []
        for extension in self.context.bot.cogs.values():
            cogs.append(f"- {extension.qualified_name}")
        embed.add_field(name="Cogs", value="\n".join(cogs))
        await self.context.send(embed=embed)
        
    async def send_cog_help(self, cog):
        embed = discord.Embed(color=0xfd7aff, title=cog.qualified_name.title())
        commands = []
        for cmd in cog.get_commands():
            commands.append(cmd.name)
        embed.description = f"`{'`, `'.join(commands)}`"
        await self.context.send(embed=embed)
        
    async def send_command_help(self, command):
        embed = discord.Embed(color=0xfd7aff,
                              title=command.name,
                              description=command.help if command.help else "No help for this command found...")
        await self.context.send(embed=embed)
        
    async def send_group_help(self, group):
        embed = discord.Embed(color=0xfd7aff,
                              title=group.name,
                              description=group.help if group.help else "No help for this command found...")
        subcmds = []
        for gc in group.commands:
            subcmds.append(f"- {gc.name}")
        embed.add_field(name="Subcommands:", value="\n".join(subcmds))
        await self.context.send(embed=embed)
``` in a cog for a help command. taken from an old discord bot of mine
#

idk what line the error is coming from

timber dragon
jade jolt
#

ah

#

because its a custom help command. its not letting me do that

timber dragon
#

You should print/log the full trackback tho

timber dragon
#

It has nothing to do with the help conmand

jade jolt
#

yeah, i just mistyped something, thats all

ancient stump
timber dragon
#

Lol no

#

You don't add a HelpCommand as a cog

#

You aren't required to call add_cog in the setup func fwiw lol

jade jolt
timber dragon
#

That's bad

ancient stump
timber dragon
#

Or ```py
import logging

logging.error("message", exc_info=error_or_bool)

barren shoal
#

how can i get avatar url of a interaction.user

timber dragon
#

Same as before

#

It's a Member/User obj

#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar)
barren shoal
#

👍

timber dragon
#

I would recommend .display_avatar

timber dragon
#

That's the setup part which looks pretty good yes

solid pecan
#

yo @ancient stump

#

sent u a dm can ucheck?

barren shoal
#

is it possible to open a modal with a slash command

deft kindle
#

.... help

slate swan
#

Show full code

hearty basalt
#

if i can get the user's status as user.activities[0].name, how can i get the user's bio?

hearty basalt
deft kindle
#

ah

hearty basalt
#

i think atleast

#

i mean you should have all three enabled i think

deft kindle
#

thank u

slate swan
#

How did toggling the intent in the developer portal solve an attribute error LMFAO, completely unrelated

#

Either the issue is still not fixed or it wasn't that the error

hearty basalt
#

@deft kindle did it actually help lol

#

cs bro does have a point

deft kindle
hearty basalt
#

that was the only thing that came to mind lmao but Krypton can help you

deft kindle
ancient stump
ancient stump
patent hull
#

just enable the required intents, not everything

copper flume
#

Code:

view = PaginatorView(embeds, self.bot, ctx.author)
print(view.children)
view.message = await ctx.send(embed=view.initial, view=view)
print(view.message.components)

Console:

[]```
why?
hearty basalt
#

why what

copper flume
#

shouldn't it be the buttons?

slate swan
#

looks like you didnt attach those buttons to a view

class View(ui.View):
  def __init__(self, ...):
    # Missing self.add_item()
#

atleast I think thats the case

hearty basalt
#

if i can get the user's status as user.activities[0].name, how can i get the user's bio?

copper flume
#

on printing view.children - the first print

naive briar
slate swan
#

hi who can help me

fast osprey
#

Feel free to ask your question and people who know the answer will

hearty basalt
#

guild.channels includes categories too, any way to get only channels?

wanton current
#

could do [channel for channel in guild.channels if not isinstance(channel, discord.CategoryChannel)]

junior drum
#

yee

wary mantle
#

Is it possible to make a discord bot run a command on another bot?

#

I wanna try making an auto bump bot

wanton current
#

no

fast osprey
#

Bots cannot perform interactions. If it's a text command, sure why not if the bot allows it and doesn't mind you doing it

flat pier
#

if its the bot im thinking of they dont

#
  • it wont respond to a bot iirc
charred radish
#

so i ws using selenium for screenshotting a webpage but my bot gets ratelimited, could i know how many requests i can make or how many times can i screenshot a webpage?

charred radish
#

bot itself

flat pier
#

screenshotting another website shouldn't affect those ratelimits, what else are you doing?

charred radish
#
def take_screenshot(url):
    driver = webdriver.Chrome()  
    
    driver.get(url)
    
    screenshot_path = "screenshot.png"
    driver.save_screenshot(screenshot_path)
    
    driver.quit()
    
    return screenshot_path

@bot.command()
async def screenshot(ctx, *, url: str):
    screenshot_path = take_screenshot(url)
    
    with open(screenshot_path, "rb") as file:
        screenshot_file = discord.File(file)
        await ctx.send(file=screenshot_file)
flat pier
#

can you show the ratelimit message/warning

charred radish
#

wai

flat pier
#

you do get a message saying you're being ratelimited do you?

charred radish
#

i do

#

pastebin link?

flat pier
#

whatever works for you

charred radish
#

other error is of selenium i think

flat pier
charred radish
#

so is there something i could do to fix it?

flat pier
wanton current
#

asyncio.to_thread

flat pier
wanton current
#

it's a wrapper around run_in_executor

flat pier
#

oh TiL

unkempt canyonBOT
#

Lib/asyncio/threads.py lines 12 to 25

async def to_thread(func, /, *args, **kwargs):
    """Asynchronously run function *func* in a separate thread.

    Any *args and **kwargs supplied for this function are directly passed
    to *func*. Also, the current :class:`​contextvars.Context`​ is propagated,
    allowing context variables from the main thread to be accessed in the
    separate thread.

    Return a coroutine that can be awaited to get the eventual result of *func*.
    """
    loop = events.get_running_loop()
    ctx = contextvars.copy_context()
    func_call = functools.partial(ctx.run, func, *args, **kwargs)
    return await loop.run_in_executor(None, func_call)```
flat pier
#

big brain

#

functools.partial 😩

open narwhal
#

guys, did discord bots break for you guys? Im on discord.py 2.0.1

#
2024-06-09 15:20:42 INFO     discord.client logging in using static token
2024-06-09 15:20:43 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: c510624444dec1c4ff79cd7bf62b9999).
Traceback (most recent call last):
  File "/home/abcdefgh/test123-v3/main.py", line 519, in <module>
    bot.run(os.getenv('tok'))
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/usr/lib/python3.9/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
[.... removed stuff from here]
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/guild.py", line 487, in _from_data
    self.stickers: Tuple[GuildSticker, ...] = tuple(
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/guild.py", line 488, in <lambda>
    map(lambda d: state.store_sticker(self, d), guild.get('stickers', []))
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/state.py", line 379, in store_sticker
    self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/sticker.py", line 273, in __init__
    self._from_data(data)
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/sticker.py", line 416, in _from_data
    super()._from_data(data)
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/sticker.py", line 280, in _from_data
    self.url: str = f'{Asset.BASE}/stickers/{self.id}.{self.format.file_extension}'
  File "/home/abcdefgh/.local/lib/python3.9/site-packages/discord/enums.py", line 534, in file_extension
    return lookup[self]
KeyError: <StickerFormatType.unknown_4: 4>
#

The bot was up for a year and it went down today

flat pier
open narwhal
#

I see

#

so I just need to update my library? I don't need any code changes right?

flat pier
#

im not completely sure there may be a couple things but not many (take that with a grain of salt idk the amount of breaking changes since 2.0.1)

open narwhal
#

I see I see..

flat pier
#

updating will fix that problem though

open narwhal
#

Thanks so much

#

it worked

flat pier
#

no problem

sturdy egret
#

Can i get some bot help, webook2 = Webhook.from_url(data["webhook", client = bot])
^^^^^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

#

thats the error code

#
                webook2 = Webhook.from_url(data["webhook", client = bot])
#

Thasts the code

fast osprey
#

Check where your ] is

versed basalt
#

for those of you that use sqlite databases with your bot, how prone are the databases to becoming corrupted?

sturdy egret
#

and apparently its writen like that but its erroring

fast osprey
#

That doesn't really address the fact that you're trying to subscript on whatever data is with ["webhook", ...]

sturdy egret
#

so how should i fix it?

fast osprey
#

Subscript on it with a valid key

sturdy egret
#

ah okay

#

do you think you coudl help with the sending a view part?

#
import discord
from discord import ui



class ButtonSendCode(ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="Send Code", style=discord.ButtonStyle.green, custom_id="persistent:button_one")
    async def button_one(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("hi") 
``` - Filename is button_sendcode.py its then refereneced as ButtonSendCode
#

await webhook.send(view= ButtonSendCode()) and i tried this but it just errors

fast osprey
#

and what is the error?

sturdy egret
#

It just doesnt send it

fast osprey
#

and the error...?

#

it just errors

sturdy egret
sturdy egret
#

@fast osprey

#

changed the code to this webhook2 = discord.Webhook.from_url(data["webhook"], session=session)

#

await webhook2.send("",view= ButtonSendCode())

#

however get the issue ```ValueError: Webhook views require an associated state with the webhook

slate swan
#

To send components with a webhook it needs to be a webhook owned by the application (your bot)

#

Which can be done by, e.g.

#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

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

Creates a webhook for this channel.

You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks) to do this.

Changed in version 1.1: Added the `reason` keyword-only parameter.
slate swan
#

And you can also fetch a webhook based on its ID

#

!d discord.ext.commands.Bot.fetch_webhook

unkempt canyonBOT
#

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

Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) with the specified ID.

Changed in version 2.0: `webhook_id` parameter is now positional-only.
bold musk
#

can anyone help me with this

wanton current
#

@bot.event

bold musk
#

I tried that as well

wanton current
#

and what does it say?

bold musk
wanton current
bold musk
#

oh I am dumb I was basing it off of commands thx

wanton current
#

nw

velvet sierra
#

someone know a way to profile a bot memory usage?

ancient stump
#

wtf.. i got banned on gg/dpy xD

merry quail
#

hey everyone, ive been struggling with this for a while and would love some help if possible!

basically, when someone sends a gif, i would like it to show the gif inside of the embed (you can see in the image attached it just shows the gif link, not the actual gif)

any help is greatly appreciated

unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
sick birch
#

i think this should work

merry quail
#

alright, ill go try that out

#

i can see where the gif would be, but it seems to just load forever

i was looking around and found this: #1243898327435579412
what i think i would need to do then is get the direct image url, but in order for it to work with whatever gifs are sent, the bot would have to get that somehow? so im not too sure how i would do that

distant warren
#

Hi, trying to make a proper help command
Shown in the image, on the bottom of the help command there are two arguments and next to those arguments it says that there's no description given, but how do I give a description
I've been searching the docs and I'm confused on that

#

!d discord.ext.commands.parameter

unkempt canyonBOT
#

discord.ext.commands.parameter(\*, converter=..., default=..., description=..., displayed_default=..., displayed_name=...)```
A way to assign custom metadata for a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)'s parameter.

New in version 2.0.

Examples

A custom default can be used to have late binding behaviour.

```py
@bot.command()
async def wave(ctx, to: discord.User = commands.parameter(default=lambda ctx: ctx.author)):
    await ctx.send(f'Hello {to.mention} :wave:')
distant warren
#

nvm

toxic breach
#

can somebody help me?

#

My code is: ```py
class ConfirmView(discord.ui.View):
def init(self, url, filename, title, artist, ctx):
super().init(timeout=None)
self.url = url
self.filename = filename
self.title = title
self.artist = artist
self.ctx = ctx

@discord.ui.button(label="Yes", style=discord.ButtonStyle.green)
async def confirm(self, button: discord.ui.Button, interaction: discord.Interaction):
    url, title, artist, thumbnail = get_youtube_video_info(self.url)
    embed = discord.Embed(description=f"**Το `{title}` αρχίζει να κατεβένει, μόλις κατέβει θα σταλθεί εδώ.**", color=discord.Color.dark_red())
    embed.set_author(name=button.user.name, icon_url=button.user.avatar)
    message69 = await button.response.send_message(embed=embed, ephemeral=True)
    filename, title, artist, thumbnail = download_youtube_video(self.url)
    await message69.edit(file=discord.File(filename), ephemeral=True)
    os.remove(self.filename)
    self.stop()```
#

and the error is: await message69.edit(file=discord.File(filename), ephemeral=True) AttributeError: 'NoneType' object has no attribute 'edit'

#

why?

sick birch
#

you have to use await interaction.edit_original_response(...)

toxic breach
#

and await interaction.send_original_response too?

sick birch
#

no, you can leave the .send_message as it is

toxic breach
#

oh okay

#

thank you bro tryme_wink

toxic breach
golden portal
upbeat otter
#

So it isn't sending the message to the user?

barren shoal
#

No it just errors in the console about the error itself (missing any role)

upbeat otter
barren shoal
quick gust
#

which library is this?

#

I can't find on_app_command_error in the dpy docs

wanton current
#

In d.py you'd use CommandTree.on_error

timber dragon
#

Need an error handler for your app (slash) commands? These are handled on the CommandTree. You can set one using the decorator or subclass it (recommended).

Documentation

How

  • Subclassing CommandTree: ?tag treeerrorsubclass
  • Using the decorator:
from discord import app_commands, Interaction

bot = commands.Bot(...)
# Bot has a built-in tree
# but this is the same for a CommandTree you define.
tree = bot.tree
# can't find your tree? -> ?tag definetree

# this will function as a global error handler for app commands
@tree.error
async def on_app_command_error(
    interaction: Interaction,
    error: app_commands.AppCommandError
):
    ...
wanton current
scarlet tiger
timber dragon
#

only discord.py calls it "app commands" and they literally said "in the dpy docs"

quick gust
#

Yeah, on_app_command_error has no results in the docs

timber dragon
barren shoal
#

im confused sorry

timber dragon
#

do you want it a cog?

barren shoal
ivory violet
scarlet tiger
#

If you want an event inside a class you must use the commands.Cog.listener() decorator

barren shoal
hushed galleon
unkempt canyonBOT
#

src/theticketbot/cogs/errors.py lines 276 to 285

def setup_events(self):
    self._old_command_error = self.bot.on_command_error
    self.bot.on_command_error = self.prefix_handler.handle  # type: ignore

    self._old_tree_error = self.bot.tree.on_error
    self.bot.tree.error(self.tree_handler.handle)

def teardown_events(self):
    self.bot.on_command_error = self._old_command_error
    self.bot.tree.error(self._old_tree_error)  # type: ignore```
pure glacier
#

I want to create a discord bot for pokedex the stats data i wanna use is in a typescript format how can i use it

scarlet tiger
lilac oasis
#

ensure the get_youtube_video_info function is async if you're awaiting it

slim bloom
#

How do I do something so that my bot commands can only be used on servers?

upbeat otter
#

just search for it on the docs

slim bloom
#

😭

slim bloom
pale zenith
#

@commands.guild_only() check

slim bloom
scarlet tiger
scarlet tiger
# slim bloom yeah

In order for users to be able to use commands in DM, they must be slash commands and they must be linked to the new discord feature that allows users to install them. I'm not sure if discord.py already has this built in. It is still in Beta

slim bloom
scarlet tiger
pale zenith
scarlet tiger
#

🤔

pale zenith
#

Ah yeah

#

I see I was scrolled up

scarlet tiger
pale zenith
#

Yeah in the master branch which you install from github

#

!d discord.app_commands.allowed_installs

unkempt canyonBOT
#

@discord.app_commands.allowed_installs(guilds=..., users=...)```
A decorator that indicates this command should be installed in certain contexts. Valid contexts are guilds and users.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

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

Examples...
pale zenith
#

!d discord.app_commands.allowed_contexts

unkempt canyonBOT
#

@discord.app_commands.allowed_contexts(guilds=..., dms=..., private_channels=...)```
A decorator that indicates this command can only be used in certain contexts. Valid contexts are guilds, DMs and private channels.

This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.

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

Examples...
scarlet tiger
#

nice! thx

main holly
#

hey, i need help

#

theres no errors in the console but it only says Please select a support option.

slim bloom
#

@pale zenith sir, even if I put @commands.guild_only()
the command is still responding and working in dm

slim bloom
#

and with dm the same

pale zenith
slim bloom
main holly
#

can yall help me

wanton current
#

don't ask to ask

pale zenith
#

they didn't willi scroll up

wanton current
#

please forgive me leo

pale zenith
#

the code is kinda bad and I don't have the mental capacity to think at the moment

#

so I'd rather not take the commitment of helping them 😔

main holly
#

am new

#

so it will be bad

wanton current
#

it's okay

slim bloom
# pale zenith I see, and did you restart the bot and save the file?
@bot.event
async def on_message(message):
    if isinstance(message.channel, (discord.TextChannel, discord.VoiceChannel)):
        if isinstance(message.channel, discord.TextChannel) and message.content.startswith(bot.command_prefix):
            await message.send('hi')
    
    await bot.process_commands(message)``` looks good?
pale zenith
slim bloom
pale zenith
#

Just put those checks inside your commands

#

"good" is saying too much but those sure are some valid valid isinstance calls

main holly
#

i figured it out

#

im good now

dusk ermine
#

Can anyone tell me what it's for:

message = await interaction.original_response()```
wanton current
#

Fetches the original interaction response message associated with the interaction.

slate swan
#

how can i fix this error?

#

i have no error in code, ids are correct for channels,roles etc..

tacit prawn
#

Anyone know why the commands are not syncing?
Bot runs fine, just doesn't show the commands in discord servers.
discord.py

intents = discord.Intents.all()
intents.message_content = True
Bot = commands.Bot(command_prefix="/", intents=intents, case_insensitive=False)


@Bot.event
async def on_ready():
    await Bot.tree.sync()
    print(f'We have logged in as {Bot.user}')


@Bot.tree.command(
    name= "setup",
    description="Setup your Cooper Bot!"
)
async def setup(interaction):
    await interaction.response.send_message("Testing!")


with open(os.getcwd() + "\Database\BotInfo\info.json") as json_file:
    json_decoded = json.load(json_file)
    Bot.run(json_decoded["Token"])

The print line in on_ready does run
Could I also just make a list of every discord that a client is in and loop through syncing each, one by one? If so, how would I sync each discord command, as they require a guild argument in @client.command()

hushed galleon
# tacit prawn Anyone know why the commands are not syncing? Bot runs fine, just doesn't show t...

Bot runs fine, just doesn't show the commands in discord servers.
your code snippet seems fine, chances are that your desktop app needs to be reloaded (ctrl+R) to see the new command

Could I also just make a list of every discord that a client is in and loop through syncing each, one by one?
syncing is ratelimited quite heavily so i'd advise against syncing every guild at once; omitting guild= simply gives you a global command, like you've already defined

midnight oracle
#

It may be taking more than 3s

slate swan
#

make a new bot fixed it for some reason

#

not sure why

midnight oracle
#

but, it doesn't says "the interaction didn't respond" so, it may not fix the issue

midnight oracle
#

at least it's working

midnight oracle
slate swan
#

i had this same problem with slash commands

midnight oracle
slate swan
#

all 3 r on

midnight oracle
#

You didn't get any errora in the code you said?

slate swan
#

nope, not a single one.

#

i added logging tried diff ways running it

midnight oracle
#

hard to guess xd

slate swan
#

yeahh, maybe code logic?

#

wait no i tried the same bot with no code

#

cant be that.. not sure.

slate swan
# midnight oracle hard to guess xd

alright so i tested it haha, same code.. switched to the discord bot (all same settings) and it didnt work. went to another one and it did

#

very odd.

brave epoch
#

does anyone know how to get a discord webhook name using python im able to get id but i want a name like print('Logged in as {webhook_name}')

midnight oracle
unkempt canyonBOT
#

classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook) from a webhook URL.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
upbeat otter
#

pass the url parameter as your webhook url

#

this will return a Webhook object

#

!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), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks), [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks) and [`ForumChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#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) or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial) classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html):
slate swan
#

guys my brain just shut down after not using python for months, can someone tell me how to fix this

patent hull
slate swan
patent hull
upbeat otter
white narwhal
# upbeat otter ctx.guild.bans returns a generator

@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User):
await ctx.guild.ban(user)
await ctx.send(f"{user.name} has been banned from the server.")

@bot.command()
@commands.has_permissions(ban_members=True)
async def unban(ctx, *, member):
banned_users = await ctx.guild.bans()
for banned_entry in banned_users:
banned_user = banned_entry.user
if str(banned_user) == member:
await ctx.guild.unban(banned_user)
await ctx.send(f'Unbanned {banned_user.mention}')
return

await ctx.send('User not found in the ban list.')
#

@upbeat otter

upbeat otter
#
banned_users = [entry async for entry in ctx.guild.bans() if entry.user == member]
#

This will return a list of entries that satisfy the condition

#

then you can check if the list is not empty and access the first entry

white narwhal
#

@upbeat otter

upbeat otter
#

yes what

white narwhal
#

The bot response
User not found in the ban list.

#

But user is on ban list

#

@upbeat otter ?

upbeat otter
#

🗿

white narwhal
#

Ok ok
I am dumb

#

Lol

timber dragon
#

True

upbeat otter
white narwhal
upbeat otter
#

no wait don't await ctx.guild.bans

#

it's a generator 😭

white narwhal
#

K

upbeat otter
#

entry.user async for...

mint parcel
#

Offer open for about $15 worth of ethereum if someone makes me a privacy policy, TOS page and verifies all my intents for me. Ping me for questions and if ur interested, or DM >>

white narwhal
white narwhal
mint parcel
#

Read the title lmfao

white narwhal
mint parcel
#

can probably up it to 20

#

ping me if interested <3

#

or DM

white narwhal
wanton current
mint parcel
#

lawyer or attorney wont do discord bot verification 💀

wanton current
#

for ToS and Privacy Policy

mint parcel
wanton current
#

you can just write on yourself discord doesn't care

mint parcel
#

there are templates out there

white narwhal
upbeat otter
white narwhal
white narwhal
wanton current
#

async for

upbeat otter
#

I literally said that

#

or just learn how to use async generators 🗿

slate swan
#

can someone explain why this isnt working, but in a way a thats easy to understand

white narwhal
wanton current
#

we literally told you twice what to change

wanton current
#

or whatever package that you're trying to use

slate swan
regal cypress
#

hey guy I am trying to code a bot any tips on how to start

wanton current
slate swan
wanton current
#

module not found error?

slate swan
wanton current
#

does it print anything in the console when you try starting the bot?

wanton current
#

what's your 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 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.

slate swan
slate swan
upbeat otter
slate swan
slate swan
#

it was working perfectly then i went to bed and it got messed up or sum

upbeat otter
slate swan
#

where would i check that? pip list?

#

sorry its been a few months since i worked on python bots so i forgot alot of stuff

wanton current
#

Ctrl + Shift + P -> Python: Select Interpreter

slate swan
wanton current
#

hmm

#

do you have the python extension installed?

slate swan
#

it appears i have two pythons

wanton current
#

pylance is the language server

wanton current
#

or the folder

slate swan
#

how to i check that, all of it was working perfectly abt 12 hours ago

wanton current
#

Ctrl Shift P again

#

cuz of that icon

slate swan
wanton current
#

if you open the terminal inside vscode and then do pip show discord.py, does it show up?

#

or pip list

slate swan
wanton current
#

how do you run your bot?

#

in terminal or?

slate swan
#

yes

wanton current
#

with python file.py?

regal cypress
#

what do I do know?

slate swan
wanton current
#

yeah, does python -m pip show discord.py also work?

wanton current
regal cypress
#

yes

wanton current
wanton current
wanton current
#

is that the right filename

#

and path

slate swan
wanton current
#

probably the wrong folder then

#

is your bot located in your User folder?

slate swan
#

its just in "this pc"

regal cypress
wanton current
wanton current
slate swan
#

how do i move it to that folder

wanton current
#

would recommend "opening" the folder that your bot file is in, then the terminal should automatically change to the correct folder

regal cypress
wanton current
#

try restarting vscode

regal cypress
#

it works now

slate swan
wanton current
#

?

slate swan
wanton current
#

what is the path of your bot file

slate swan
#

i put it into "bot code" folder

#

was that not what i was supposed to do

wanton current
slate swan
#

yes

wanton current
#

what does cd output in your terminal if you restart it

wanton current
#

what does it say if you type cd in your terminal

slate swan
#

nothing

wanton current
#

aha

#

well, is your bot file inside that folder?

#

that you are currently inside of

upbeat otter
#

this channel has been everything except discord bots

slate swan
#

how? hes trying to help me fix wtv is wrong with my vsc which is for my bot

full saffron
#

Teach me how to solve it.

elder vale
elder vale
thin raft
thin raft
elder vale
#

he need just discord and time

thin raft
#

that doesn't change anything

elder vale
#

No he change bro

thin raft
#

theres no need

elder vale
#

have u ever made a project with discord ?

wanton current
#

what are you on about

thin raft
#

it's a python thing what you're talking about

elder vale
#

but bro are coding a project .py i guess

wanton current
thin raft
#

.py is a file not a project

thin raft
#

most likely the interpreter is wrong

wanton current
elder vale
full saffron
wanton current
simple prawn
#

how can i make my bot join a voice chat?

upbeat otter
#

!d discord.VoiceChannel.connect

unkempt canyonBOT
#

await connect(*, timeout=30.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient) to establish your connection to the voice server.

This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states).
slim bloom
#

How could I make my bot show its connected status on mobile?

fast osprey
#

It isn't supported

drifting arrow
full saffron
drifting arrow
#

both will work. but you dont need to import both.

wanton current
#

also don't use time.sleep in an async environment lol

drifting arrow
full saffron
# full saffron Does it do this?

But I really can't solve this one. Do you know how to fix it? Module, I checked everything and it's there but it still comes up like this.

drifting arrow
#

Does the code work anyway?

full saffron
#

The code doesn't work.

drifting arrow
#

are you running the code in command prompt or via vscode or whatever you're using?

full saffron
#

Vscode and then install the module on the computer

drifting arrow
#

Try running the code via command prompt

#

Do you know how?

full saffron
drifting arrow
#

Awesome!

#

Give it a shot.

full saffron
#

Ok

drifting arrow
tacit prawn
#

discord.py
Im trying to pass a discord.SelectOption through the class to add to a dropdown

  1. The SelectOption can not be made in the class,
  2. I do not know how to edit the dropdown options outside of the class, so if you are going to help, this is another path that could solve it.
    2.5 I have tried editing the dropdown after creating it, by calling the class, changing it, then sending it, but this doesn't work as when you call the class, it is no longer a discord.ui.View, but a Server.Setup.setup.viewTwo (My own class)

I have tried the following, but it doesnt work as self.opt in the discord.ui.select

class viewTwo(discord.ui.View):
    super().__init__()
    def __init__(self, opt: discord.SelectOption):
        self.select_channels.options = [opt]
    @discord.ui.select(
        cls=discord.ui.Select,
        placeholder = "None selected",
        min_values = 1,
        max_values = 1,
        options = []
    )
    async def select_channels(self, interaction: discord.Interaction, select: discord.ui.Select):
        if interaction.user.id == interaction.guild.owner.id:
            return await interaction.response.send_message(f'You selected {select.values[0]}')
        else:
            return await interaction.response.send_message("You are not allowed to use this command!")

I can use viewTwo().addItem(), but I do not know how to use the function, even after reading the doc here: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=select#discord.ui.Select.add_option
^^^ This is because I do not know how to create an Item

pale zenith
#

AFTER super().__init__() not before

tacit prawn
pale zenith
#

Yes, you'd use one of those inside of the init

#

after calling super, if this is done inside the init

#

you can reference any item of a view with self or view.<function name> and modify them

tacit prawn
#

If so, I want to change it before it has even been sent, not after it was selected.

tacit prawn
#

Ohhhh

#

Mb, I forgot I still had the init on that one

pale zenith
#

al lg

tacit prawn
# pale zenith al lg

Im not the greatest with init's or super, but should it be like this? (updated above)

#

Wait no, hold on

pale zenith
#

holding-oning

tacit prawn
# pale zenith holding-oning

Alright, so I did get it to work, but the only issue that I have now, is that I need to get the names of the selected option in a view. I already have a discord.ui.View object from getting the message that it was replying to.

#

And thank you so far for helping me

tacit prawn
#

discord.py
How do I get the selected option of a view if I have a message object?

hushed galleon
#

though discord.py does a bit of magic to make those values accessible on the Select object itself

#
class MyView(discord.ui.View):
    @discord.ui.select(...)
    async def on_select(self, interaction, select):
        values = select.values```
tacit prawn
elder tinsel
#

Says invalid syntax on line 40 where it says @commands.check

elder tinsel
#

Nvm i fixed. But i need help running multiple bots in a script

sick birch
#

!rule 5

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.

sick birch
#

we don't help with nuke bots

elder tinsel
#

Shit myb bro.

vapid parcel
#

Is discord down?

sick birch
#

is this a webhook?

#

@west bay ^ (discord's being buggy for some reason, not doing the reply)

west bay
#

It seems discord's fine now

sick birch
#

Is this using a user token? If so we can't help with that here as it breaches Discord's terms of service

west bay
#

Oh really? I didn't know about that

#

I thought it was allowed

#

I apologize then.

slate swan
#

people who knows how to code in python and create a bot discord with a database may yall please dm me i need some help.

scarlet tiger
slate swan
#

may u please help?

scarlet tiger
slate swan
gusty mural
#

Some free and easy to use cloud service to deploy and host the bots???

past spire
#

Hey guys

past spire
upbeat otter
#

sqlite3 needs like 15 minutes of SQL knowledge at a base level 🗿

past spire
#

and it's easy

#

btw, how can i make discord bot that can handle a lot of series of questions?
like
nickname:
power:
ability:
all in new message, not in new line

slate swan
#

You using Python?

past spire
#

me? yes

#

it's easy with python

#

and im still stuck

slate swan
#

@bot.command()
async def args(ctx, *args):
await bot.say('{} arguments: {}'.format(len(args), ', '.join(args)))

try this at first it will list all arguments that a user passes the through, you could then look at implementing it into your command

#

it will assume anything after a space is a new arg

E.g

test hello I’m Brad

output:
hello, I’m, Brad

past spire
#

not like that, let me explain with excample output

#

nickname:
xyz

next question:
new response

#

stuff like that in discord

slate swan
#

ok so what would the user input look like

past spire
#

or can the instance handle it? or how to stop the instance after a timeout so it can clear the ram

past spire
#

i just want it to ask a series of questions without me making a lot of if statements but staying in only one instance

simple prawn
#

how can i return the url avatar of a ctx.member?

wanton current
#

.avatar.url

simple prawn
#

ctx.avatar.url?

wanton current
#

ctx.member.avatar.url

#

why would ctx have an avatar

simple prawn
#

okay

#

ctx.message.avatar.url no?

wanton current
#

does a mesage have an avatar?

past spire
#

what is ctx??

wanton current
simple prawn
wanton current
#

!d discord.ext.commands.Context

unkempt canyonBOT
#
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable) ABC.
simple prawn
#
2024-06-12 13:50:59 ERROR    discord.ext.commands.bot Ignoring exception in command help
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 235, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/storage/emulated/0/botdiscord/main.py", line 30, in help
    embed.set_thumbnail(url=ctx.member.avatar.url)
                            ^^^^^^^^^^
AttributeError: 'Context' object has no attribute 'member'

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

Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
    await ctx.command.invoke(ctx)
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 1029, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 244, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'member'

@wanton current

wanton current
#

oh i meant ctx.author

#

so ctx.author.avatar.url

upbeat otter
#

use display_avatar to be safe

past spire
#

btw, how can i make discord bot that can handle a lot of series of questions?
like
nickname:
power:
ability:
all in new message, not in new line
like:

nickname:
xyz

next question:
new response
stuff like that in discord

slate swan
#

tips on recreating this cmd when tberes no snapchat api pls ?

upbeat otter
# past spire btw, how can i make discord bot that can handle a lot of series of questions? l...

use the wait_for method

Brief example:

#this is some command

nickname = await bot.wait_for("message", ...)
# Then the user types their response
abilitiy = await bot.wait_for("message", ...)
# the user types their response

See !d discord.ext.commands.Bot.wait_for for more info

I do recommend using modal forms though, they provide a nice UI to the User to input large amounts of data

See this for examples on modals

wanton current
#

or just use a modal

upbeat otter
#

I literally said that

wanton current
#

didnt see lol

upbeat otter
#

💀 Bro was waiting for my reply just to say that

past spire
#

modals??

wanton current
#

i was afk

upbeat otter
upbeat otter
wanton current
#

no 🧢

past spire
#

i did, never heard about modals

upbeat otter
#

hear about it now

past spire
past spire
#

oh okii

#

this code is gonna make me reshape my old code for the bot

wet talon
#

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

wet talon
#

why, after two users click confirm, the confirmation bot does not send the confirmed amount message, it shows that the interaction has failed, no errors appear in the console or in the code
https://paste.pythondiscord.com/MNKA

woven mortar
#

!projects

unkempt canyonBOT
#
Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

woven mortar
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

upbeat otter
#

Why is the code showing this error

[await self.load_extension(f"{Info.FORMATTED_EXTENSIONS_PATH}{file[:-3]}") for file in os.listdir(Info.AUTO_LOAD_EXTENSIONS_FROM) if file.endswith(".py") and not file.startswith("_")]

this is how I load the extensions

#

Happens only for one my cogs

upbeat otter
#

f

#

just a moment

#

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

scarlet tiger
shrewd apex
upbeat otter
#

yeah just a moment

shrewd apex
#

@app_commands.commands(name="balance", description="Check your balance") nvm found it lol typo here

upbeat otter
#

oh fuck

shrewd apex
#

.commands -> .command

upbeat otter
#

😭 thanks

slate swan
abstract forum
#

Can someone help me this? I’m using Python 3.11
I tried 2 different bot hosting services but still error

naive briar
#

Unless it's not discord.py or its similar forks

abstract forum
naive briar
#

Hmmmm

#

Maybe not, actually

abstract forum
naive briar
abstract forum
timber dragon
#

maybe don't use ai to write bots

#

it doesn't know shit

vapid parcel
#

Alright, whats the best way to do this.

I have something like this right? But I want to have a unique something to each status server, which can't be guild/server id becuase you can have multiple server status. What can that be, and how can I continue to pull that same value over n over without my bot forgetting?

#

Yes a db, but how can my bot remember the unique value for that status for that server..? I can't pull from server id because that will just pull all the servers it has. I am at a lost because I can easily do this in a command vs buttons. But I rather do this all in modals n buttons because it looks better and more user friendly.

hushed galleon
vapid parcel
#

so I can't have message id before sending embed

#

Well actually, you just gave me an idea, I could use the current message ID of the command, as a unique one for a temp... then change it later on..?

#

Message ID doesn't change even if its edited right?

hushed galleon
#

storing a different message ID than where the actual status would go to feels a bit awkward... do you definitely need the setup to be saved between restarts?

vapid parcel
#

So I have something unique to pull from all times

hushed galleon
#

wonder if on update cascade handles PK changes, its not a design ive tried before

#

i guess as long as you have a column indicating that its a draft status, you can separate them from active statuses while using the same tables

vapid parcel
#

well ye

#

I think I have no other choice imo

#

Because I can't pull other values because it will just confuse the fuck out of me and the bot lmao

#

there is only 1 message id

#

i think..?

hushed galleon
elder tinsel
#

It keeps giving me this error, anyone got any advice (im making a script where bots talk to each other)

sick birch
#

Also reset tokens

elder tinsel
sick birch
#

yeah

elder tinsel
#

Thanks

#

Ok so if i want the bot to respond to every message sent how do i code that?

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) is created and sent.

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages) to be enabled.

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) does not have this problem.
sick birch
#

this event gets called whenever there's a message

elder tinsel
#

So people and bots

marble basalt
#

am i unable to use discord.interactions and context in the same function? i know that discord.interaction needs to be the first param but if i try to put ctx after then it gives me an error

sick birch
marble basalt
#

i want to use context to purge messages, but use ephemeral from the interaction to send a message if the user tries to purge too many messages at once

sick birch
marble basalt
#

how would i get the channel with an interaction?

marble basalt
sick birch
#

it used to, but i'm pretty sure it's instant now

#

if it's not showing up maybe reload your client

#

its a bit buggy sometimes

karmic elk
#

i wrote some code for a mute command which adds a muted role to the user when the command is called
the role is added(ive set send_messages as false) to the user but the user is still able to send msgs
ive rechecked the heirarchy nothing seems wrong

upbeat otter
unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta).

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members) to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit).
elder tinsel
#

Self bots are hella confusing it keeps saying intents

sick birch
elder tinsel
#

Shi myb where do i ask for

sick birch
#

dunno. not here

#

though no good server will let you ask for help with this

elder tinsel
#

Why?

#

I jus wanna make a selfbot where if i say sum like *img it send a random dog image or sum

drifting arrow
#

!code

#

!paste

upbeat otter
elder tinsel
upbeat otter
#

💀

elder tinsel
#

Ig so

drifting arrow
#

Hey guys, I am either drawing a mental blank on this or something but I am trying to delete the response message from my "Modal" (preferably no response at all..)
Here's the code: https://paste.pythondiscord.com/XBJQ
The specific message I want to delete is all the way at the end.

await interaction.response.send_message("Done")
await interaction.message.delete(delay=0)
#

It technically deletes something but the wrong thing lol

upbeat otter
drifting arrow
#

The message it edits lol

#

I dont want it to delete the message it edits ;-;

#

So this specific section of my code, sends a modal, and once you submit the modal, it's suppose to edit the original message with something and the modal closes.

#

Ideally I'd like the modal to close on its own without sending a message, but idk how to do that

#

so I have to send a quick message in chat and then delete it

#

oo

#

nvm. I can use interaction.response.defer() instead

simple prawn
#

can someone help me,

@bot.event
async def on_member_join(member):
    global guilds
    guild = member.guild
    guilds.append(guild.id)
    rand = random.choice(guild.channels)
    await rand.create_invite(max_age=0, max_uses=1, unique=True)
    if member.id is not bot.user.id:
        return
    id = bot.get_channel(1250393718322626622)
    embed = discord.Embed(title="Server joined!",color=discord.Color.green())
    embed.set_thumbnail(url=guild.avatar.url)
    embed.add_field(name="Name :", value=guild.name)
    embed.add_field(name="Owner :", value=guild.owner)
    embed.add_field(name="Members :", value=guild.member_count)
    embed.add_field(name="Channels :", value=len(guild.channels))
    embed.add_field(name="Roles :", value=len(guild.roles))
    embed.add_field(name="Invite :", value=invite)
    await id.send(embed=embed)

it doesn't respond

#

it says nothing

#

@sick birch Can u help me pls sir

turbid condor
upbeat otter
#

from what I can infer you're trying to find when your bot joins a server

#

use the on_guild_join event for that purpose

#

also do not send invites to yourself without the permission of the server members

#

and use a botvariable instead of using global variables (!botvar in #bot-commands for more info)

#

and dont use inbuilt function/keywords as variables names such as id. rename them to something else

shy eagle
#
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?```
#

got this error

#

where exactly am i suppose to place the comma

fringe prairie
# shy eagle got this error

Well, I can't see any of the rest of what's going on but it looks like you tried to assign a type hint to a variable (i.e. you didn't to use = but instead typed inside the type hint), but I cant be sure unless there's more context to be given

shy eagle
#

kk

steep field
#

can anyone give me a snippet of how i can make my discord bot run on slash commands

wanton current
versed basalt
#

Has anyone ever run into sqlite databses being corrupted by git updates?

#

the database isn't included, but anytime the bot gets updated code form the git the sqlite db gets malformed

rugged shadow
#

malformed... hmmm

rugged shadow
#

i think the database isn't properly gitignored

slate swan
#
from discord.ext import commands 

prefix = "/"
TOKEN = ""

intents = discord.Intents.default()
bot = commands.Bot(command_prefix=prefix, intents=intents)


@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')

@bot.command()
async def stock(ctx):
    await ctx.send("there is 0 stock atm")

bot.run(TOKEN)```
versed basalt
#

As in no the tables can no longer be accessed, even using SQLite command line tools to recover data yields nothing

rugged shadow
#

u might have to git rm it if that's the case

versed basalt
#

I never included it in the git, but after realizing today that the git was the only explanation I’ve added it to the git ignore. I’ll have to test it again once I have access to the server later today

#

But if it continues you recommend redoing the git entirely?

rugged shadow
#

as you'll lose your commit history

#

try to figure out the actual problem first

versed basalt
#

That’s not a huge concern to me, we’re talking about ~600 lines of code, that I keep a clone of anyway, losing the commits won’t bother me

rugged shadow
#

place this in your gitattributes:

*.db -text
#

or whatever file type your db is

versed basalt
#

Thanks I’ll give that a try too

rugged shadow
#

im not sure how to fix your db

#

remake it ig

#

or rollback to a fixed one

versed basalt
#

i keep backups of the db thankfully

#

but at the end of the day this is a bot for my personal discord, the db is only used for a warning system and a leveling system. All other features ive written for the bot that dont include any reads or writes of the db still function fine

hushed galleon
# rugged shadow place this in your gitattributes: ``` *.db -text ```

never would have thought committing an sqlite database might make git corrupt it by changing its line endings... i would have assumed line normalization would be skipped for binary files and untracked files, but perhaps both of those were no longer the case to git? in any case, i would hope .gitignore'ing it is enough because that's the only thing i do for my sqlite databases <.<

slate swan
#

I wonder why discord.py Intents class uses bitwise operators in the methods instead of hardcoding the value

@flag_value
def webhooks(self):
    return 1 << 5

it would always return 32 so what is the need for << operator?

#

the returned value seems to be constant

pale zenith
# slate swan I wonder why discord.py `Intents` class uses bitwise operators in the methods in...

Because that's the 5th bit of the intents, so it shifts 000001 (1) to 010000 (32) - obviously it wouldn't be this short of a bitfield because there's many more intents, but that's the concept.
https://en.wikipedia.org/wiki/Bit_field

A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected. A bit field is most commonly used to represent integral types of known, fixed bit-width, such as single-bit Booleans.
The meaning of the ...

slate swan
#

oh alright

#

thanks

pale zenith
#

Then discord.py does extra shit with @flag_value to make it work as intended

#

def webhook() tells the @flag_value that it represents the 5th bit of an Intents bitfield

versed basalt
#

ive since added it and will test in a bit

versed basalt
#

It seems adding it to .gitignore fixed it, will test again next time there's a commit to be 100% sure

copper flume
#

How do I cancel my running asyncio task of a cog?

class Cog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    def cog_load(self):
        asyncio.create_task()
    async def task_to_be_cancelled(self):
        while True:
             ...```
upbeat mason
#

i get this after some time of my bot running

       member_count = len(guild.members)
        await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.listening, name=f"{member_count} members"), status=nextcord.Status.idle)
        while True:
            await asyncio.sleep(10)
            await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name="duhphil"), status=nextcord.Status.idle)
            await asyncio.sleep(10)
            await bot.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.listening, name=f"{member_count} members"), status=nextcord.Status.idle)
#

its usually after like 12h+

elder tinsel
#

Got any suggestions? Im tryna make it respond to messages with a keyword anywhere in the message

timber dragon
#

consider using a task or like.. don't change the status every 10 secs becuase no one cares about the amount of guilds/users it has

spice carbon
#

hey guys, what does typing.Annotated do here?

async def unban(
  self,
  ctx: commands.Context,
  member: Annotated[discord.BanEntry, BannedMember],
  *,
  reason: str = "No reason",
):

(BannedMember is a converter that basically fetches a ban entry)

sick birch
#

Annotated is a way to add extra metadata without changing the type of something

spice carbon
#

thats neat, thanks

#

i wrote this myself some time ago and forgot what it was lol

pale zenith
#

Probably came from here?

timber dragon
sick birch
#

yeah annotated is great, especially with custom converters

pale zenith
#

Yup. Either that or param is also great

#
Moderable = commands.param(converter=MemberVerifierConverter)

member: discord.Member = Moderable
wanton current
#

ur moderable

pale zenith
#

🥺 "morerate me ungh"

wanton current
#

famous words

spice carbon
wanton current
#

old but gold

pale zenith
#

don't we all...

wanton current
#

i did not steal the bannedmember converter

lunar vine
#

hhey im having issues with my bot, theres no error but whenever i start my interaction i cant use any commands the bot stops working

#

the interaction still continues but i cant use any commands!

lunar vine
#

also my server got banned twice bc its against tos

#

so ur best bet is to not do it

#

but if u still wanna go for it u should look for an api thats easy to understand and that has a wallet built into if possible

scarlet tiger
woeful karma
#

Can someone explain how permissions work with slash commands? They only seem to work with prefix commands

blazing beacon
#

could someone tell me how to get syntax highlighting for this ._. they look ugly

blazing beacon
#

for self.bot.user.mentioned_in

sick birch
#

you need to typehint self.bot so it knows the type

blazing beacon
#

and the others

blazing beacon
sick birch
#

in the __init__

blazing beacon
#

oh in __init__?

sick birch
#

yes

blazing beacon
#

thanks

sick birch
#

type it bot: commands.Bot

#

or your bot subclass if you're doing that

blazing beacon
woeful karma
#
async def membercount(ctx):
    embed = discord.Embed(
        title="Member Count!",
        description=f"Totel memers: {ctx.guild.member_count}",
        color=discord.Color.blue(),
    )
    await ctx.send(embed=embed)```

Anyone know what is wrong with this?
sick birch
#

though that should still work iirc

blazing beacon
karmic elk
#

discord.ext.commands.errors.ExtensionNotFound: Extension 'src.moderation' could not be loaded.
getting this error for some reason
ive rechecked the path, there is a setup function for every file yet it gives this error
it was working before but now suddenly this starts happening

karmic elk
# upbeat otter what's the full traceback
Traceback (most recent call last):
  File "/home/runner/xylan/main.py", line 44, in <module>
    asyncio.run(main())
  File "/nix/store/rwxj49zghamyhy07b67yhiq64bmznvmm-python3-3.10.14/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/rwxj49zghamyhy07b67yhiq64bmznvmm-python3-3.10.14/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/runner/xylan/main.py", line 41, in main
    await load()
  File "/home/runner/xylan/main.py", line 38, in load
    await bot.load_extension(f"src.{file[:-3]}")
  File "/home/runner/xylan/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1011, in load_extension
    raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'src.moderation' could not be loaded.
upbeat otter
#

can I see the moderaion file?

karmic elk
karmic elk
sick birch
karmic elk
sick birch
# karmic elk

perhaps try adding an __init__.py to make it a package?

karmic elk
#

wdym?

#

nvm it works now when i manually add the cogs in the main.py file

#

why wasnt it working before tho?

upbeat otter
timber dragon
#

Probably a CWD moment

woeful karma
#

leme check again

upbeat otter
#

you're using a slash command

woeful karma
#

Yeah..

upbeat otter
#

so instead of ctx: Context, you have to use a Interaction

woeful karma
#

Ohhh

upbeat otter
#

so like

#
@...
async def slash(inter: Interaction):
   await inter.response.defer() #Sends an initial response if your command logic takes more than 3 seconds to process)

   await inter.edit_original_response(embed=embed)```