#discord-bots

1 messages · Page 371 of 1

slate ravine
shadow vigil
shadow vigil
#

so you giving a int instead of a str, change the game typehint to int

#

and shall all be fixed

shadow vigil
slate ravine
shadow vigil
#

if you want the game name maybe map them into a dict

slate ravine
shadow vigil
# slate ravine I'm sort of confused on what you are saying but i will say what i am trying to d...

I am unsure either of how to explain this to a newbie.

what you have to do is create a dict object and put every number as a key and the value as the game name,

here an example of using a dict but that's too complex to a newbie

games = {
  1: "Mag Game",
  2: "Lob Game",
  3: "Game Night"
}

game = int(input("enter a game: "))
print("the game you entered is", games.get(game, "Mag Game"))

what a newbie will originally do is:

if game == 1:
  print("the game you entered is Mag Game")
elif game == 2:
  print("the game you entered is Lob Game")
elif game == 3:
  print("the game you entered is Game Night")

exam the first code sample, and learn and understand how dict.get works and how to use dicts

slate ravine
shadow vigil
untold orbit
#
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    from pymongo.mongo_client import MongoClient
  File "/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/pymongo/__init__.py", line 90, in <module>
    from pymongo.collection import ReturnDocument
  File "/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/pymongo/collection.py", line 40, in <module>
    from bson.raw_bson import RawBSONDocument
  File "/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/bson/raw_bson.py", line 57, in <module>
    from bson import _get_object_size, _raw_to_dict
ImportError: cannot import name '_get_object_size' from 'bson' (/home/runner/xeph-hunchothreat/.pythonlibs/lib/python3.8/site-packages/bson/__init__.py)

``` in my discord bot. i really dont know what is wrong.
shadow vigil
slate ravine
untold orbit
#

sorry i just fixed it. just had to uninstall pymongo and reinstall it

hushed galleon
#

seems about right, you get the permissions on the second screen once you've selected a server

#

those two are your oauth scopes, bot and applications.commands

#

i cant recall what it looked like in the early days, but afaik every bot invite link shows the same two screens, oauth scopes first, then bot permissions

(if the oauth link doesn't include the bot scope, then you won't see the second screen)

#

whats actually freaky is if the first screen shows "Join servers for you" 🥴

slate swan
lucid kite
lucid kite
lucid kite
slate swan
#

so instead of pip i have to do py -m pip?

slate swan
lucid kite
slate swan
lucid kite
#

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

slate swan
lucid kite
slate swan
lucid kite
#

no sorry. i don't do calls, open a help thread.

slate swan
#

oh wait i think ik the problem

lucid kite
#

your token is visible there btw

slate swan
#

its okay

#

its whatever

#

i will just reset it and i fixed it btw

#

thanks for all the help

solid pecan
#

Yo i have a question about cogs

#

when i write a cog in a different file, for example: mycog.py

#

How can i import it to the main file so i can use it

shrewd apex
#

u would have to load it as an extension

#

!d discord.ext.commands.Bot.load_extension

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

basically u with ur bot u would do await bot.load_extension("cogs.mycog")

solid pecan
#

What about await bot.add_cog(“…”)

#

whats the difference between the 2?

#

or do i need load extension to be able to use add cog?

shrewd apex
vapid parcel
#

Is there a channel where I can get ideas for my bot?

vapid parcel
#

You could just auto load the cogs instead of manually loading them

upbeat otter
vapid parcel
#

But then they think thats the only way ya know, so its better if you just teach them the auto loading imo

timber dragon
#

Also that's just an example

#

Also also, you don't "load' a cog

#

You load the extension which calls a function called setup which is where most people add a cog to the passed bot

solid pecan
#

i have another question.. i noticed people using this:

async def setup_hook():
    for file in os.listdir("cogs"):
        if file.endswith(".py"):
            await bot.load_extension(f"cogs.{file[:-3]}")```
#

cant we just do: @bot.event async def on_ready(): await bot.load_extension("cogs.cog") print('Cog loaded') to auto load the cog?

shrewd apex
#

thats what he meant by auto loading yeah

#

it goes over the cogs folder and adds each cog

#

also try not use on_ready for this use the setup_hook

solid pecan
shrewd apex
#

on_ready is called multiple times thoroughout a bots lifetime setup_hook is called only once

solid pecan
#

oh so i will load the extention multiple times if i use onready

shrewd apex
#

yeah

#

the code would be called multiple times in an unpredictable manner due to resuming gateway connections to discord

solid pecan
shrewd apex
#

it would load only 1 particular cog if u have multiple cogs u would need to use a for loop

solid pecan
#

wait

#

i thought we only use 1 cog and put all of the functions there

shrewd apex
#

u can use multiple cogs

solid pecan
shrewd apex
#

yep

#

usually u group similar commands under a cog

#

u can have several categories of commands

solid pecan
#

ok thanks

timber dragon
#

More like common misinformation
People should know how it works instead of copypasting some code and thinking it works like magic

timber dragon
fast osprey
#

Also setup_hook isn't an event

hearty basalt
#

@merry cliff one more question

#

so i've made a tickets command with a button that creates said ticket. it works fine, though the button doesn't work after restarting the button. is there an easy way to keep the button functional even after restart?

wanton current
hearty basalt
brisk plume
hearty basalt
brisk plume
merry cliff
#

Why do u need so many devs for a game bot

hearty basalt
merry cliff
#

That might be too many cooks in the kitchen

#

!rule paid

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

merry cliff
#

That is also a thing which might apply here idk

hearty basalt
#

chatgpt cookin for me rn

#

chatgpt is half my kitchen

fast osprey
#

chatgpt thinks that 3 isn't a prime number. It's more stupid than a toddler but confident in its stupidity

hearty basalt
#

i love how it sometimes writes code incorrectly, i point it out and folks blame me for it

#

like cmon man

#

yet it cooked up rn

wanton current
#

keyword sometimes

hearty basalt
#

hell yeah

slate ravine
#
async def stats(interaction: discord.Interaction, ctx):
    stats_count = ctx.guild.member_count
    em = discord.Embed(description=f'`Current Member Count`: {stats_count}')
    await interaction.response.send_message(embed=em)``` 

Error: parameter 'ctx' is missing a type annotation in callback 'stats'
wanton current
#

you dont get ctx in app_commands

#

only interaction

slate ravine
wanton current
#

use interaction.guild instead

slate ravine
#

oh yea

#

thank you

wanton current
#

np

shy eagle
#

willi

#

could i have a word with u

#

in dms

ripe fossil
#

my problem is im trying to make a log tracker(counts the number as i use the command) I can't get it to update the number in my Data.json file

timber dragon
#

does assigiing it to data also update the file?

#

consider using a db like sqlite

#

you need to rewrite the whole json for that to work which can and will corrupt the file at some point

ripe fossil
#

is there a way i can make the tracker without having to do all that?

#

im just confused on how to get it to udpate the number after I use the command, like why doesn't the
log_number = int(data["Log_Number"]) log_number += 1
work?

#

it sends the message with the Log number, but doesnt update the number to 2

cloud dawn
ripe fossil
#

what?

#

i get data is just data in memory , but HOW do i update it

timber dragon
slate swan
#

bruh wht is worng with the server icon

slate swan
#

is there a way i can make a script that automatically vote for a bot in top.gg

wanton current
slate swan
#

?

shrewd apex
fast osprey
#

May want to read their terms of service

slate swan
shrewd apex
slate swan
shrewd apex
#

then u should pick a better site which allows such automation

slate swan
#

such as?

#

what matter is method not the site, and then you can try it on your own risk

shrewd apex
#

!tb

#

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

Maybe wait a bit more than less than 60 seconds

#

Sharing code would be useful as well

shrewd apex
#

paste ur code and send the complete traceback

slate swan
hearty basalt
#

mann how tf do slash commands work

#
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix=commands.when_mentioned_or("."), intents=intents)
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)



@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=1247794415582318652))
    print('ready')

shi does NOT print 'ready'

slate swan
#

By typing / and choosing the command you want to execute

hearty basalt
#

folks i know how to use a slash command ion kno how to make one

shrewd apex
#

are u doing bot.run ?

slate swan
#

The intent name for message content is message_content, not messages

hearty basalt
#

yh this the actual command

@tree.command(name="name", description="description")
async def slash_command(interaction:discord.Interaction):
    await interaction.response.send_message("command")
``` but the print('ready') doesn't even work soo
slate swan
#

ok i change my question how did u learn it without someone telling u "tos"

shrewd apex
#

intents.message_content = True

slate swan
#

Line 6, rename messages to message_content if you want your command to work

#

messages is included in Intents.default()

shrewd apex
hearty basalt
#

but i understand what you mean tho

#

i ain runnin the client

shrewd apex
#

u dont need both bot and client

rain hedge
#

could someone please explain quickly what cogs are?

shrewd apex
#

u can just use it like

@bot.tree.command()
slate swan
hearty basalt
#

ohhh

shrewd apex
#

bot comes with a tree out of the box

hearty basalt
#

ima try rq

shrewd apex
#

same with @bot.event

hearty basalt
#

i still need

tree = discord.app_commands.CommandTree(bot)
``` right
slate swan
#

is asking wht cogs are is against tos too?

slate swan
hearty basalt
#

folks yo profile looks cool ash

rain hedge
slate swan
#

profiles*

slate swan
hearty basalt
slate swan
#

oh thx

#

whats good about it

#

i never expected this compliment

#

it might be against tos to compliment my pfp

hearty basalt
#

😭

#

@shrewd apex

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

tree = discord.app_commands.CommandTree(bot)


@bot.tree.command(name="name", description="description")
async def slash_command(interaction:discord.Interaction):
    await interaction.response.send_message("command")

@bot.event
async def on_ready():
    print(f'{bot.user} successfully logged in!')
    await tree.sync(guild=discord.Object(id=1247794415582318652))
```discord.errors.ClientException: This client already has an associated command tree. 

explain im dumb man terms
slate swan
#

nah fr mentioning tos is crazy 💀
its literallt like halmet u can kill with it but u shouldnt stop teaching ppl how to use halmet bc he might kill someone

pale zenith
hearty basalt
pale zenith
#

Nope

rain hedge
#

no

hearty basalt
#

i can't do await tree.sync(guild=discord.Object(id=1247794415582318652)) then right

#

i'm genuinely lost with the tree n slash commands icl i'm too slow 😭

hearty basalt
#

can yall tell me why this pops up when i don't even have such a command in my code 😭

pale zenith
cloud dawn
cloud dawn
#
# after disabling all components we need to edit the message with the new view
# now when editing the message there are two scenarios:
# 1. the view was never interacted with i.e in case of plain timeout here message attribute will come in handy
# 2. the view was interacted with and the interaction was processed and we have the latest interaction stored in the interaction attribute
async def _edit(self, **kwargs: typing.Any) -> None:
    if self.interaction is None and self.message is not None:
        # if the view was never interacted with and the message attribute is not None, edit the message
        await self.message.edit(**kwargs)
    elif self.interaction is not None:
        try:
            # if not already responded to, respond to the interaction
            await self.interaction.response.edit_message(**kwargs)
        except discord.InteractionResponded:
            # if already responded to, edit the response
            await self.interaction.edit_original_response(**kwargs)
#

Disable all just disables all components in the view, stop, stops the view and confirm is a variable to let the view know it's confirmed, just a var.

#

This is the _edit function await self._edit(view=self) self gets passed, self is the current class. This just edits the view when it gets changed.

#

There are enough comments to get you started and I recommend running the code yourself and change things and look into it.

#

Yes and no, you want to disable the view before stopping because otherwise the user could still click the buttons but the app won't respond. And you want to stop the view because otherwise it would use too much resources at some point.

#

In this specific case the confirm is true, so buttons get disabled, edit pushes the disabled to Discord and then the view gets stopped. That gets returned to the command function and then you could do further logic.

#

Ah a paginator, then you'd edit the View to show the new text. I might've an example..

hushed galleon
#

!pypi discord-ext-pager is the lib you can install for it

unkempt canyonBOT
cloud dawn
#

verinoice

hushed galleon
#

basically the same as the code in paging.py, just a few changes and er, a readme

cloud dawn
cloud dawn
#

lmao

#

Just made me feel old ducky_lemon

clever spade
#

!pate

#

!paste

#

https://paste.pythondiscord.com/P4FA

Anyone know why the logging on this wont work, ive tried adding & removing logging statements, ive also tried another bot with this code and it didnt work so ik its the code, although i use this exact code with different channel ids on a different bot, and ik its not a perm problem since bot has admin + all intents

chilly cloud
#

is there any way I can write this code to run faster?

#

I feel like having 3 for loops within a for loop might run slowly

fast osprey
#

It's generally never a good idea to agonize over "might"

#

Run the thing and profile it if you're worried

slate swan
versed basalt
#

Anyone here have experience with integrating their bot with a Plex Server?

fast osprey
#

Going from 3 comprehensions to 1 loop would be faster but it's still O(n). It won't be noticeable

untold orbit
#
@client.event
async def on_connect():
  print("Huncho is Online")
  print(f"{len(client.guilds)} Servers. {len(client.users)} Users.")
  await status()
  try:
   await client.add_cog(AntiChannel(client))
   print("AntiChannel Cog Loaded")
  except Exception as e:
    print(e)

i cant tell if my cog wont load or this wont work.

class AntiChannel(commands.Cog):
    def __init__(self, client):
        self.client = client
        db = mydatabase["hunchodb"]

    @commands.Cog.listener()
    async def on_guild_channel_create(self, channel):
      whitelisted = db.find_one({"_id": channel.guild.id})["whitelisted"]
      async for i in channel.guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_create):
          if i.user.id in whitelisted:
            return
          anti = db.find_one({"_id": channel.guild.id})['antinuke']
          if anti is False:
            return


          await channel.guild.ban(i.user, reason="Anti-Nuke: Creating Channels")
          await i.target.delete(reason="Anti-Nuke: Deleting user created channels")
          logs = db.find_one({"_id":channel.guild.id})["logschannel"]
          c = self.client.get_channel(logs)
          embed = discord.Embed(title="Anti-Nuke", description=f"{i.user} has created a channel, and has been banned by Anti-Nuke", color=0x2f3136)
          await c.send(embed=embed)
``` help pls
fast osprey
#

You should not be using on_connect for one time setup things. It runs several times and effectively randomly

#

Also if you don't want someone creating channels, why do they have the permission to do that in the first place?

quick gust
#

I can subclass Context and use CustomContext in prefix commands, is there anything similar I can do for interactions? bcs custom context requires get_context for prefix commands but idk if there's something similar for interactions

fast osprey
#

There's no library support for custom Interactions, because Interactions are a type published by discord with a defined structure

fast osprey
#

You could just not let them have those perms

untold orbit
#

some ppl aint that smart 🤷

fast osprey
#

If they're too stupid for that, what makes you think they're smart enough to not give someone rank to kick your bot first?

untold orbit
#

why you put the bot above those roles. trust everything in my bot is very easy to setup.

fast osprey
#

But they're stupid

#

You just said that you don't trust your own users

untold orbit
#

you get a message that says it only works if it is above the member.

#

trust i know my setup works. i just need help with the function itself.

chilly cloud
#

yo, I wanna add a buy item feature, but since each server has a unique shop, is there a way to create a drop down menu of items in a shop from accessing the database?

fast osprey
#

Idk fam, you could just have people use the systems that already exist and are far more reliable than your bot

#

Every couple of days I hear someone crying about an anti-nuke bot that got compromised or didn't work because they're inherently flawed

untold orbit
#

okay so are you gonna help or not, i didnt ask for your opinion?

fast osprey
#

lol my help is to use the systems that actually work instead of this hacky stuff, your call if you don't want that help

untold orbit
#

so if you weren't gonna help with wt i sent then why say anything to me ?

fast osprey
#

That is the help. You just don't want it

untold orbit
#

and i wanted to make my own anti-nuke is there a problem with that?

fast osprey
#

There is, because as said before it is flawed

untold orbit
#

and exactly why i asked for help? r u not using your brain?

fast osprey
#

Flawed at its concept

#

Not execution

untold orbit
#

okay the concept is for me to deal with? not you?

fast osprey
#

I'm telling you how to actually prevent things from happening in a guild. If you don't accept that, your goal isn't actually to keep people safe but to double down on this naive implementation

untold orbit
#

okay and how does that help me with my code at all whatsoever?

fast osprey
#

By helping with the core goal, which is to prevent these things from happening

untold orbit
#

but is that wt i asked for?

fast osprey
#

Are you familiar with the XY problem?

untold orbit
#

is that wt i asked for tho ?

fast osprey
#

Are you familiar with the XY problem?

untold orbit
#

completely dodged my question then wanted me to answer yours?

fast osprey
#

It is related to your question

#

Good help seeks to understand what your core goal is and helps you with that, rather than blindly helping with the (flawed) proposed solution you already have

#

If your goal is not to prevent these things from happening, then my help doesn't apply

fast osprey
fast osprey
#

You can subclass Select then pass the options you want into the super constructor

#

Also implement callback

chilly cloud
fast osprey
#

Are you familiar with how to subclass?

chilly cloud
fast osprey
#

Yes exactly

chilly cloud
#

what does super constructor and callback mean

fast osprey
#

You can make your own class inheriting from Select. You will want to two things in it:

  • override __init__. In this you will call the super().__init__(). You can pass whatever you want like you would to a normal select, including options=

  • override callback(self, interaction). This does whatever you want when the select gets interacted with

chilly cloud
fast osprey
#

How do you inherit from any class?

chilly cloud
#

oh righ

#

lemme try it

chilly cloud
fast osprey
#

discord.ui.Select

chilly cloud
#

does ui select affect slash commands?

#

I thought it was for like buttons or something

fast osprey
#

Those are dropdowns

#

Or do you mean option parameters on a command?

chilly cloud
#

I think thats why I was a lil confused lol

fast osprey
#

!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), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.

[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#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) documentation.

Warning

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

Examples on there

#

My b

chilly cloud
#

I was reading the docs and it said that it was a list of suggestions instead of something compulsory, should I just return an error message or something if they type something that isnt in the database?

fast osprey
#

Yeah your options are to either do validation in a command, or to present them with a Select

chilly cloud
#

alright

wet talon
#

i need help with buttons

#

the bot does not respond to buttons

fast osprey
#

You shouldn't be using interaction.message.edit, you can just respond with interaction.response.edit_message

wet talon
#

I want the bot to edit the message

fast osprey
#

and that's what interaction.response.edit_message does

wet talon
#

its still not working @fast osprey

fast osprey
#

code? error?

wet talon
#

I didn't get any error

#

the bot still doesnt edit message

#

@fast osprey any idea?

fast osprey
#

You have if statements. Have you done any debugging to see how those are behaving?

wet talon
#

nope

#

so? @fast osprey

scarlet tiger
wet talon
#

I asked many people for help but no one knows the answer BRUH

wet talon
wanton current
fast osprey
#

yeah do some debugging

scarlet tiger
wanton current
#

if the if statement doesn't pass, nothing happens in the callback

wet talon
fast osprey
#

You can just put print statements in your code to see what's happening

wanton current
#
# If this evaluates to true, run code
if interaction.user.id == self.user_id:
    embed = interaction.message.embeds[0]
    embed.description = embed.description.replace("None", interaction.user.mention)
    await interaction.response.edit_message(embed=embed)
    await interaction.response.defer()

# Else, do nothing
wet talon
#

I still don't understand what you're talking about

scarlet tiger
fast osprey
wet talon
#

I want the user who clicks the "Send" button was added to an earlier message

#

I want the bot to edit it

scarlet tiger
fast osprey
#

You don't want that method

wet talon
#

when someone clicks sending
bot will edit sending litecoin and instead of none his nickname will appear

wet talon
fast osprey
#

You should debug to see what your callbacks are doing

wet talon
#

python debugging?

fast osprey
#

or just print statements

wet talon
#

how to do print statements

quick gust
#

you print()

wet talon
#

Can you add these print statements to code

wet talon
quick gust
#

no I don't spoonfeed

quick gust
wet talon
#

but how should I add it and where?

fast osprey
#

Wherever in your code you want to see what's happening

quick gust
#

by using the combination of p r i n t ( ) keys on ur keyboard

wet talon
#

I added this and it didn't help me

scarlet tiger
wet talon
#

they told me not to use them

scarlet tiger
wet talon
#

still not working

scarlet tiger
storm saffron
#

Does anyone know what the kwargs for discord.utils.get() specifically for guild.text_channels?

#

does it use the attributes that discord.TextChannel uses?

fast osprey
vapid parcel
#

Yo

#

How do people make select menus/drop down menus, show options you have already selected when you load the menu again

#

Yes its from a db, but how to do it in dpy.

#

I know its like a very stupid question and prolly simple, just wanna know how to do it tho lol.

hushed galleon
#

well, the idea would be to get the data that you need, turn that data into options, and add them to the select

vapid parcel
#

But it shows selected already..?

hushed galleon
#

oh you mean how that appears? presumably default=True on one of the options

vapid parcel
hushed galleon
#

huh, i didnt know default worked for multiple options, guess that makes sense

vapid parcel
#

So its just default?

hushed galleon
#

yeah, looks like it

#

oh wait a minute, i think i can replace my /inbox staff add|list|remove commands with a MentionableSelect...

#

o, i need dpy latest to get default_values...

hushed galleon
fast osprey
#

Holy crap is that a ticket thread

vapid parcel
vapid parcel
vapid parcel
#

I think it was a ticket thread

vapid parcel
red palm
#

hi leonardo!

pale zenith
#

Hi. what the FUCK is this chat

vapid parcel
vapid parcel
red palm
vapid parcel
#

you to famous for him shrug

pale zenith
#

idk man it's like 3am for them why would they reply lmao

red palm
craggy notch
#

OK, are the videos necessary here?

pale zenith
#

You'll probably get banned for spam before they wake up

red palm
#

Yes

vapid parcel
#

Just a lil fun, no harm done tbh

pale zenith
#

Plus they have a funny voice

vapid parcel
flat pier
vapid parcel
red palm
#

fr tho

#

im sry

vapid parcel
#

Alr ill see yall later cuz imma get banned prolly for just some fun :/

red palm
#

plz dont ban me

vapid parcel
#

Vencord banned me within like 3 seconds cuz I was asking for help one time GoofySkull

#

That was a good day

#

Fr 😭

craggy notch
#

As a reminder, we need to remain on topic. Keep in mind whether your videos are disruptive or not.

#

If you would like a place to be silly (although please don't meme dump) we have the OT channels.

vapid parcel
vapid parcel
#

Fr you a W

craggy notch
#

I'm actually struggling to play the videos so there's not much I can do anyway.

red palm
#

@craggy notch needs to be promoted

vapid parcel
#

They are just him talking in a nerd voice tbh

craggy notch
#

I downloaded one, and yeah, it's fine.

vapid parcel
#

Who are you?

#

I don't know you blud, don't think I know you blud.

craggy notch
#

It's just off-topic here. This is a topical channel for people to discuss and get help with developing Discord applications/bots.

vapid parcel
red palm
#

sorry!

vapid parcel
#

We truly sorry lol. We were honestly just bored n wanted something to do, we prolly won't do it again, if we do just mute us for like 3 weeks or something lol.

karmic harness
#

I am new and I making a discord bot and I have completed the main.py and I have yet to add the cmd but I don't know how it is done and I went to another website and copied and pasted the code but still it is not working, maybe that code It is not connecting to my bot

hushed galleon
#

!paste your code with any tokens removed and we can look at it

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.

hushed galleon
#

if your command isnt running, maybe you're missing the message content intent?

vapid parcel
#

It would print in your console ^

drifting arrow
#

What's the command grouping thing called again?

#

nvm found it. :D

#
from discord.ext.commands import Cog, Bot
import discord
from discord import app_commands
from discord import Interaction
from discord.app_commands import guild_only, command

class TestClass(Cog):
    def __init__(self, bot:Bot, config:dict):
        print("[Cog] TestClass has been initiated")
        self.botBot = bot
        self.config = config
    
    poll = app_commands.Group(name='poll', description='polls for polls and polling')

    @poll.command(name='create', description='Create a poll')
    async def create(self, interaction: discord.Interaction, question:str, option_one:str, option_two:str):
      await interaction.response.send_message("Results go here.", ephemeral=True)
    
    @poll.command(name='info', description='Info on a poll')
    async def info(self, interaction: discord.Interaction, poll_id:int):
      await interaction.response.send_message("Results go here.", ephemeral=True)
``` found my example file that had it :D
upbeat otter
drifting arrow
upbeat otter
wet talon
#

bot doesnt responding to butttons

shrewd apex
# wet talon bot doesnt responding to butttons

line 83, 98, 93

-    async def reset(self, button: discord.ui.Button, interaction: discord.Interaction):
+    async def reset(self, interaction: discord.Interaction, button: discord.ui.Button):
#

its ordered wrong

shrewd apex
#

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

shrewd apex
#

oh check ur on_message u have a try block but no except

#
try:
  ... # code here
except: # <-- u need to add this
  ...
wet talon
#

where should i add this? @shrewd apex

shrewd apex
#

corresponding to same level as line 43

wet talon
#

but now the last message is not sent with the buttons

#

@shrewd apex

shrewd apex
#

u didnt send the view anywhere

#

if u dont send the view how will the buttons show up?

fast osprey
#

As friendly advice, if you're not even familiar with how a try/except works you're going to have a very painful time trying to implement an advanced library like dpy. It'll make a lot more sense if you build up with focused exercises on core concepts rather than trying to build a skyscraper from scratch

#

Yesterday you didn't know what a print was

shrewd apex
#

werent u already given some resources yesterday for this?

full seal
#

what are discord bots

chilly cloud
#

yo guys, im using aiosqlite and im using a cursor, but im getting this when Im reading data from it

hushed galleon
chilly cloud
#

it worked from another part of my code, not sure why it dont here

hushed galleon
#

and what is being formatted in your embed?

chilly cloud
#

wrong part of code wait

solid pecan
#

Hey guys my hybrid command is not working for some reason. im not sure why

chilly cloud
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.

solid pecan
#

wait no thats the wrong script

chilly cloud
solid pecan
#

class MyCog(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.content.lower() == 'hello' or  message.content.lower() == 'hi' or message.content.lower() == 'hey':
            await message.channel.send(f"Hello, {message.author}")

    @commands.hybrid_command(name = "ping", description = "Tells you the ping")
    async def ping(self, ctx):
        await ctx.send(f'> Pong! {round(self.bot.latency * 1000)} ms')  


async def setup(bot):
    await bot.add_cog(MyCog(bot))```
#

this is my hybrid command script but not sure why it wont work

hushed galleon
# chilly cloud https://paste.pythondiscord.com/G5IA
'item_name': (name[2] for name in guild_shop if item_dict['item_id'] == name[1]),
'item_description': (desc[3] for desc in guild_shop if item_dict['item_id'] == desc[1]),
'value': (value[4] for value in guild_shop if item_dict['item_id'] == value[1])
``` these are indeed generator expressions
chilly cloud
#

how do I format them correctly

hushed galleon
#

seems like what you're trying to do is a JOIN on guild_shop(item_id) so thats what you should rewrite your query into

hushed galleon
hushed galleon
solid pecan
hushed galleon
#

did you reload [Ctrl+R] your client?

#

well er, your discord application specifically, not the bot

#

discord has had a kind of long-standing problem with new slash commands not appearing on clients, so thats my first guess whenever a slash command doesn't seem to show up

fast osprey
#

"Doesn't work" isn't descriptive of what's actually happening

solid pecan
fast osprey
#

Your call to sync will also tell you if you synced that command

upbeat otter
solid pecan
#

what does it do?

wanton current
#

sync the app commands

upbeat otter
#

Better if someone could link Asher's gist explaining commandtree

solid pecan
#

i tried to sync like this: synced = await bot.tree.sync()

#

and the slash command appears now

#

im not sure if its the sync that fixed it or it was just discord being slow..

upbeat otter
vapid parcel
#

"Your organization's usage has exceeded its included quota
Your projects can become unresponsive or enter read-only mode. Please upgrade to the Pro plan to ensure that your projects remain available."

"5.242 / 5 GB (105%)"

How we are using so much, is there a way to see whats using this or what..? I am really confused on how we are using so much just for a discord bot..?

It was literally always <%1 but yesterday it started to go up, and its the only thing GOING up. And I have NO clue why.
I am just trying to see what Table could be doing this or what could be causing this stuff, it has never done this before tho.

I am only asking here because I know others use supabase, so if someone could help then please do lol

flat pier
#

5gb is not a lot

vapid parcel
wanton current
#

bandwidth or storage?

flat pier
#

egress is bandwidth iirc

vapid parcel
#

^^

wanton current
#

is this a free plan or smth

hushed galleon
#

does anything else read your database?

wanton current
#

bc that's nothing

#

i get 20 TB/mo

pale zenith
#

damn 5gb is shit

vapid parcel
#

The rest are using less than 1% is why I am hella confused

#

Well we have decided to ditch supabase and just host our own. This will just be easier 😁

flat pier
#

idk but looking at the supabase website it looks cringe

#

just get a good vps and throw all ur bots on that

vapid parcel
#

So just ignore my message ig shrug

vapid parcel
flat pier
#

gross but ig it works

vapid parcel
#

so we are gonna host our own postgres instead of using supabase

vapid parcel
#

don't hate on digital ocean the website that looks like it was made in 2000s 😭

flat pier
#

i dont care about what the website looks like

pale zenith
#

it's just overpriced as fuck

#

What product are you currently using?

pale zenith
vapid parcel
pale zenith
#

Like are you using droplets? which one, and what specs? (Just curious)

vapid parcel
#

Actually, I can't check, this droplet isn't mine, its my friends so I can't check XD

#

We have like multiple droplets, but this one I do not control sadly

flat pier
#

the cheapest plan is shit

#

so i can't imagine what the rest are compared to competitors

pale zenith
#

that's with italian 22% sales tax

flat pier
vapid parcel
#

Watched a video abt locations on fucking water today ngl.

Where this mofo was talking about how water is different on prices just based on location even if its the same brand

#

crazy things

flat pier
#

they dont have new shared intel locations in the U.S but they do for amd servers

pale zenith
vapid parcel
#

https://leo.might-be.gay/SK3KJI.png

pale zenith
#

if you want your server to be in the land of the "free"

vapid parcel
pale zenith
#

There isn't anything to talk about

wanton current
#

leo-might-be.italian

vapid parcel
pale zenith
#

anyway if you use droplets you're getting scammed lmfao

vapid parcel
#

Me not paying

#

so im chilling

hearty basalt
#
# allows a command to be executed if the user either has a specific role or admin perms
# for addrole & remrole:

def has_any_role_or_permission(ctx: Context):
        if any(role.name in globals.roleRole for role in ctx.author.roles):
            return True
        if ctx.author.guild_permissions.administrator:
            return True

#example:

@bot.command(name='purge')
@commands.check(has_any_role_or_permission)
logic

(roleRole is defined in globals.py)
can i somehow catch the CheckFailure error once a user tries the command without the roles or perms needed

#

or do i need to just try & except it on every command

vapid parcel
#
def has_any_role_or_permission(ctx: Context):
    if any(role.name in globals.roleRole for role in ctx.author.roles):
        return True
    if ctx.author.guild_permissions.administrator:
        return True
    return False
#

return False that should fix it. Possibly lol

hearty basalt
#

cs im tryna have it send a message like "You don't have the perms to use this command" or sumn

vapid parcel
#

Oh wait I didn't even read everything, but yes, you can catch the CheckFailure, you can use errorhandling

#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CheckFailure):
        await ctx.send('You do not have the correct role or permissions to run this command.')
    else:
        raise error```

Example
quasi bough
vapid parcel
#

Was keeping how they had it lol

quasi bough
#

i see, apologies

vapid parcel
#

nah you good

hearty basalt
vapid parcel
hearty basalt
fast osprey
#

You should not be using channel names to store shifting data. This is API abuse and discord have specifically said it is not allowed

hearty basalt
fast osprey
#

Your code looks for one specific channel in one specific guild and updates that one, regardless of which guild you're getting updated counts for though

hearty basalt
#

yh ik 😭

#

ima scrap it

slate ravine
slate ravine
hushed galleon
# slate ravine ?

supposedly that means your client UI has an outdated version of the command, so perhaps Ctrl+R reloading your client would fix it?

upbeat otter
pine saddle
#

Why does my ping command not work?

# bot.py
import os
from dotenv import load_dotenv

import discord
from discord.ext import commands


load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.all()
intents.message_content = True

bot = commands.Bot(
    command_prefix = "!",
    intents=intents,
    activity=discord.Game("placeholder"),
    )

@bot.event
async def on_ready():
    print(f'Bot is ready. Logged in as {bot.user}')

@bot.event
async def on_message(message):
    if "hello" in message.content:
        print(f'Message received: {message.content}')

        for x in range(10):
                await message.channel.send("hello"),

@bot.command
async def ping(ctx):
    print('[debug] Ping command received')
    await ctx.send("pong")

Why does my ping command not work?
Im using the exact explanation from the docs: https://discordpy.readthedocs.io/en/v2.3.2/ext/commands/commands.html#

I have the correct intents turned on in the developer portal (all of them).

The @bot.event on_message etc. all work fine.

But the bot.command doesn't do anything when i post !ping in the discord server. Also no debug print.

slate ravine
pine saddle
#

Doesn't make a difference.

wanton current
pine saddle
#

In the folder.. where my application is.
Everything else works.

pine saddle
#

Yep thats it. Thanks lol

wanton current
#

nw

vapid parcel
#

Whats an alternative to Flask, that is async

wanton current
#

quart

#

or fastapi

vapid parcel
#

Now the downside of this is, I can't run these in a thread correct?

wanton current
#

Are you trying to run them alongside your bot?

vapid parcel
#

Yes

#

API for a dashboard.

shrewd apex
#

just spin up a plain aiohttp webserver alongside

wanton current
vapid parcel
vapid parcel
wanton current
#

why would you need that

vapid parcel
#

Gotta also have it as a docs page for web developers

#

thats why I have flask

#

shouldve mentioned that 😭

wanton current
#

i mean, it's a webserver, just like flask

vapid parcel
#

Its an API while being a docs page for the web developers, so they understand how it works in the bot and how to make it work in the website side

shrewd apex
#

u could just use bot.loop.create_task(run_function_here)

#

if u dont want a seperate bot instance and be monolithic

shrewd apex
vapid parcel
#

tf is swagger 😭

shrewd apex
#

and openapi docs too iirc

vapid parcel
vapid parcel
shrewd apex
#

sounds like a good solution

zenith cove
#
async def on_command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        embed = discord.Embed(
            description="**Mention someone to unban**\n> **,unban** *(userid)*",
            color=discord.Color.red()
        )
        await ctx.reply(embed=embed)
    elif isinstance(error, commands.CommandInvokeError):
        error_message = str(error) if str(error) else "An unknown error occurred"
        await ctx.reply(error_message)```

erorr handling part of an unban command

returns An unknown error occurred: object async_generator can't be used in 'await' expression
scarlet tiger
slate swan
#

is there a way to get discord interaction object using http request?

#

any help?

fast osprey
#

What are you trying to accomplish?

slate ravine
#

!paste

simple prawn
#
import discord
from discord.ext import commands
bot = variables.bot
#code here
bot.run(variables.token)
.../0/botdiscord $ python main.py                       Traceback (most recent call last):
  File "/storage/emulated/0/botdiscord/main.py", line 43, in <module>                                               bot.run(variables.token)
    ^^^^^^^                                             AttributeError: 'Command' object has no attribute 'run'
quick gust
#

what is variables.bot?

scarlet tiger
dapper sluice
#

is there anyway to track the current duration of a song being played in a vc

#

i tried just storing the time at the start of it but that doesnt include pausing the song and what not

wanton current
#

What are you using to play the music?

dapper sluice
#

uh

#

is it taboo to say im using yt_dlp

wanton current
#

meh

dapper sluice
#

ok well im using that

wanton current
#

i forgot yt_dlp, any code?

dapper sluice
#

uh its a bit funky since i made it a couple years ago idk how the modern implementations are done but ye

#

one sec

#

tried to include the relevant stuff idk if i missed amst

spice warren
#

You don't get help with music bots here, wouldn't really talk about it here if possible

fast osprey
#

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

main holly
#

.paste

#

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

rugged shadow
# slate swan any help?

typically you expose a web server to Discord and it sends interactions to your server as POST requests

#

the other way is through websockets/gateway which idk much about

blazing beacon
#

how do i check the channeltype of the message? i saw something like Message.channel.type but i dont know what it should return

#

!d discord.Message

unkempt canyonBOT
#

class discord.Message```
Represents a message from Discord.

x == y Checks if two messages are equal.

x != y Checks if two messages are not equal.

hash(x) Returns the message’s hash.
unkempt canyonBOT
sick birch
#

the docs say what type it returns

marble basalt
#

hey, does anyone know how i can use the member object given by the on_member_join function to do things like get the members profile picture?

blazing beacon
rugged shadow
#

alternatively, read the docs here

hearty basalt
#

to get a user banned from every server the bot is in, can i loop thru the guilds and ban the user?

rugged shadow
#

yes, but... why??

hearty basalt
#
@bot.command(name='gban')
@commands.check(has_any_role_or_permission)
async def gban(ctx, user: discord.User = None):
    for guild in bot.guilds:
        ctx.guild.ban(user)
``` would something like this even work?
#

i edited it, like that?

rugged shadow
#

nvm nvm

#

discord.User with capital U

#

also await the ban call

#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake) abc.

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

completely forgot lmao 😭

vapid parcel
#

Does anyone know how the WHMCS api works for getting attachments? Are you able to download them?

slate swan
# vapid parcel https://developers.whmcs.com/api-reference/getticket/ you can get attachment, ...
drifting arrow
copper flume
#

Hi, If I do jsk py bot.http.token it says [token ommited] but gives the token when I use jsk py await ctx.send(bot.http.token) how do I fix it?

shrewd apex
#

jsk should be owner only command wdym fix it?

timber dragon
#

^ what needs fixing here? Only you can run that

fast osprey
#

I guess if you spend so much time building systems predicated on people being brain dead stupid, you start applying that to yourself

hearty basalt
#

anybodii know how buttons work

sour cloak
#

hi so i was trying fetch badges for a user using public_flags in my discord server for a project of mine but seems like the amount of badges u can get is limited is there any other way.

for this project

fast osprey
#

Not all badges are exposed on the api afaik

vapid parcel
hearty basalt
#

chat how do i restrict a button to a specific role(s)

fast osprey
#

Do whatever checks you want in the callback

drifting arrow
fast osprey
#

May want to check the rules there

hearty basalt
#

yeahh dont offer or request paid services

wet talon
#

https://paste.pythondiscord.com/MGXQ

why when the user sends a number, the bot does not send an embed message confirming this number
these are the last lines
the bot does not respond to what the user sends

sour cloak
fast osprey
#

Are you really trying to shuffle around crypto with a discord bot

sour cloak
#

maybe try debugging

wet talon
sour cloak
wet talon
fast osprey
#

"Auto mm" sure is a bunch of words

sour cloak
sour cloak
#

lol

wet talon
#

the bot has all the permissions, the same user

#

I also think the code is good, but there must be something wrong

sour cloak
sour cloak
wet talon
#

he send it

#

but he didn't read the value I wrote

fast osprey
wet talon
fast osprey
#

But you are asking for help with a bot that violates terms, aren't you?

#

Even if it's not this specific piece that is violating the terms

wet talon
fast osprey
#

Are you facilitating the transfer of financial assets?

#

Cryptocurrency are financial assets

solid pecan
#

are you trying to make something similar to halal mm? @wet talon

#

just noticed that youre in the stock server lol

solid pecan
# wet talon yes

well be careful because that server gets banned every week or so

wet talon
#

okay

#

but can someone help me or not?

solid pecan
#

its pretty complicated.. so be patient until somebody with experience can help u

wet talon
#

https://paste.pythondiscord.com/MGXQ

why when the user sends a number, the bot does not send an embed message confirming this number
these are the last lines
the bot does not respond to what the user sends

fast osprey
hearty basalt
#

if i have a url= argument in my button, it automatically sets the style of the button to url. Is there any way to force it a different style? Even if i specify a style like primary or success it uses url

wanton current
#

url buttons can only be one style

hearty basalt
#

understood

hearty basalt
#

if i have multiple buttons with long text, can i do something along the lines of how you can do \n to start from a new line

#

instead of the buttons going to the right beyond the text & embed

merry cliff
#

You can set the button row for each button

#

Each message has a limit of 5 rows with 5 buttons each

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None, sku_id=None)```
Represents a UI button.

New in version 2.0.
merry cliff
#

You can set it with the row parameter

#

@hearty basalt

hearty basalt
#

im learning buttons slow ash 😭

merry cliff
#

np

slate swan
zenith yarrow
wet talon
#

https://paste.pythondiscord.com/MGXQ

why when the user sends a number, the bot does not send an embed message confirming this number
these are the last lines
the bot does not respond to what the user sends

any ideas?

slate swan
#

bro my automm bot is broken

fast osprey
slate swan
hearty basalt
# merry cliff np

could you help me with slash commands if you ever have time? i made a whole seperate bot to test & it just doesn't work. i was following this tut:

wanton current
#

well, you're syncing the tree to the guild, but the command globally

slate swan
#

its impossible to make a userinfo with a slash command, pls explain why?

slate swan
shrewd apex
#

wdym userinfo

#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
lavish haven
#

im 99% sure i got rate limited. what now

#

either that or

#

i actually need help with something

#

can i post my code here

shrewd apex
unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

lavish haven
shrewd apex
#

paste yours

lavish haven
#

im having trouble because i tried to code this which i found somewhere, it works and apparently my bot IS synced to it as well but it doesnt show up in apps

#
async def show_join_date(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f"{member} joined at {discord.utils.format_dt(member.joined_at)}")```
#

when I sync automatically from on_ready def it also counts this as synced but it doesnt show on apps, yet it still doesnt show any errors. it should be working but its not.

#

i even made a manual sync function and it still said the same thing yet it doesnt show in apps. why?

shrewd apex
#

did u try reloading ur discord client (just hit ctrl + r)

lavish haven
#

...

#

hey asher am i stupid or am i

shrewd apex
#

if the command shows up in the synced command lists when u sync it from ur code for that particular bot then that means discord has received that data so in most cases its ur client lagging behind ducky_beer

lavish haven
#

oh i did get an error

#

Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/bot.py", line 47, in show_join_date
await interaction.response.send_message(f"{member} joined at {discord.utils.format_dt(member.joined_at)}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'InteractionResponse' object has no attribute 'send_member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show_join_date' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'send_member'

zenith yarrow
#

@fast osprey sorry the forum was closed yes I want to send another message do i need use interaction.followup("")

#

But I saw the type of .followup is webhook i don't really know what that is

fast osprey
#

interaction.followup.send

#

!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:
zenith yarrow
#

Ty

shrewd apex
#

send_member? can u paste your code

lavish haven
#

oh yeah

#

i fixed it myself i just saw the trace

#

but yeah youre right lmao im blind i said send_message

shrewd apex
#

it seems a bit inconsistent, with what u sent b4

#

then do u still get an error?

lavish haven
#

or not

#

yup.

#

Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/bot.py", line 47, in show_join_date
await interaction.response.send_member(f"{member} joined at {discord.utils.format_dt(member.joined_at)}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'InteractionResponse' object has no attribute 'send_member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'show_join_date' raised an exception: AttributeError: 'InteractionResponse' object has no attribute 'send_member'

shrewd apex
#

send_member its send_message

lavish haven
#

yeah i did that before

#

but i got the same error

shrewd apex
#

did u save ur file?

lavish haven
#

yeah

shrewd apex
#

not possible

lavish haven
#

hmmm

shrewd apex
#

u prolly made a typo somewhere or just looked at the previous errors

lavish haven
#

like maybe i didnt youre right, maybe im losing my mind i was sure it was message i mean thats literally why i changed it to member otherwise it wouldnt have been

#

no you are right im losing my mind my bad

slate swan
#

hellooo?

lavish haven
#

ight so let me break it down for you

slate swan
lavish haven
#

nvm forget it

#

wait ill actually break it down for you one sec

hasty edge
#

Yo i need help

#

im tryna code this discord bot cause I hv too much free time and want to learn smth

#

you know how each bot has its very own intent

#

how do I make mine the tag of the bot

#

like instead of using !help

#

how to make it @bot help

#

tag me so i don't forget

hasty edge
#

thanks @wanton current

wanton current
#

np

hearty basalt
#

sounds cool ash

slate swan
hasty edge
#

anyways gtg, my sis needs help with smth

slate swan
chilly cloud
stark ingot
slate swan
stark ingot
#

Wait, i did not understand your question. You can find that info from User.premium_type. It will be an int you can match to this table -> user-object-premium-types

simple prawn
#
import variables # file
@bot.command()
async def var(ctx, * var: str):
    await ctx.send(variables.ctx) #get var from file
#
2024-06-07 21:26:21 ERROR    discord.ext.commands.bot Ignoring exception in command var
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 236, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/storage/emulated/0/botdiscord/main.py", line 51, in var
    await ctx.send(variables.ctx)
                   ^^^^^^^^^^^^^
AttributeError: module 'variables' has no attribute 'ctx'

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 1169, 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 1020, 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 245, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'variables' has no attribute 'ctx'
wanton current
#

what is variables

simple prawn
wanton current
#

well, the error is pretty obvious

simple prawn
wanton current
#

?

fast osprey
#

You probably don't want a singular context shared globally across your app

mighty terrace
#

what do you think wich functions should an automod bot have? Wich would he important if you would use it?

simple prawn
scarlet tiger
simple prawn
#

no theres my token

scarlet tiger
simple prawn
#

but why

scarlet tiger
#

Additionally, the token is recommended to have its own file. I recommend a .env file

simple prawn
scarlet tiger
#

If you don't show that module I can't help you.

simple prawn
#

the ctx attribute is in the async def

wanton current
#

what is variables.ctx

scarlet tiger
wanton current
#

"it"

simple prawn
#
from discord.ext import commands
bot = commands.Bot(command_prefix="+", help_command=None)
#

@scarlet tiger

fast osprey
#

self_bot=True

simple prawn
#

nooo

scarlet tiger
simple prawn
scarlet tiger
#

Bruh

simple prawn
#
@bot.command()
async def var(ctx, * var: str):
#

THERE IS CTX

#

lmao ig

scarlet tiger
#
import variables # file
@bot.command()
async def var(ctx, * var: str):
    await ctx.send(variables.ctx) #get var from file

The problem is here "variables.ctx"

simple prawn
scarlet tiger
# simple prawn what???

I repeat. The error is in the line await ctx.send(variables.ctx). The variables module does not have that attribute.

simple prawn
scarlet tiger
simple prawn
scarlet tiger
#

🤔

simple prawn
#

💀💀💀💀

#

the file?

scarlet tiger
simple prawn
simple prawn
#

u don't know bot.

scarlet tiger
simple prawn
#

like +var <var name>

scarlet tiger
hearty basalt
#

this might be one of the funniest back & forths i've seen

scarlet tiger
#

I give up

#

🥲

simple prawn
#

...

#

i give up too

hearty basalt
#

whats the original issue again lmao

inner abyss
#

hi

scarlet tiger
inner abyss
#

@scarlet tiger

simple prawn
#

ctx.content*

scarlet tiger
simple prawn
#

like +var token

{token of the bot}

inner abyss
hearty basalt
#

never even touched the variables module i cant say nun

scarlet tiger
simple prawn
#

@inner abyss

Code studio - code editor

#

Termux - Setup thing

hearty basalt
#

coding on a phone is a royal pain in the ass

inner abyss
simple prawn
simple prawn
hearty basalt
inner abyss
simple prawn
inner abyss
simple prawn
#

like pip install ?

#

@inner abyss

inner abyss
simple prawn
inner abyss
#

@simple prawn where is py💀

simple prawn
#

file manager sry

inner abyss
#

ok thanks

simple prawn
#

u're wlc

flat pier
slate swan
#

word

stiff gorge
#

.

orchid thistle
#

pls someeone help me

#

i made a discord bot and i coded all command in main.py and then the bot started lagging so i made another file called help.py and now when i type help command the console shows no command named help was found

#

pls some one help me

#

@desert heart

shrewd apex
#

the bot lagging has no such relation to having all commands in a single file unless ur doing something very resource intensive or very bad code, its most likely network latency

shrewd apex
orchid thistle
#

see

#

@shrewd apex

shrewd apex
#

that wouldnt help at all if ram usage is high then ur using a ton of memory somewhere else, also replit machines are pretty underpowered wouldnt really trust their analytics

#

u need to load help.py as a cog if ur using stuff in another file

#

!paste paste ur help.py content here

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.

orchid thistle
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.

orchid thistle
shrewd apex
#

the code u wrote wont work

orchid thistle
shrewd apex
#
from discord.ext.commands import Bot, bot # <-- No such thing as "bot"
#

u need to make a cog

orchid thistle
#

ok

#

so i should make a file named cog.py or folder named cog ?

shrewd apex
#

but this wont help with your ram usage or memory problem btw

slate crest
#

Asking because these commands work when i dont have the event in the code, but when i put the event in, the event itself works fine, but the other commands cease to exist, it doesnt even recognise the prefix as a prefix (like otherwise youd get a message saying ?me isnt a command)

inner abyss
#

@slate crest

#

where do you host your bot?

slate crest
# inner abyss <@530636413394223111>

are you asking regarding the aforementioned snippet or in general? the snippet i dont host anywhere, its just a project that i run on my pc. But on bigger projects i simply used to buy some replit cycles, dont know if its changed now

ancient stump
#

does anyone know a good hoster?

fast osprey
#

The examples given don't go into the nuance that you do not need a cog at all to have an extension. In many cases the cog is just unnecessary messy boilerplate

fast osprey
coarse ridge
#
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.guild_messages = True
intents.members = True

bot = commands.Bot(command_prefix='.', intents=intents)

vouches = {}

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

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    await bot.process_commands(message)

@bot.command()
async def vouch(ctx, member: discord.Member = None):
    if member is None:
        await ctx.send("Hey! To use this feature, please mention a user. Example: `.vouch @user`")
        return

    vouch_count = vouches.get(member.id, 0)
    vouch_count += 1
    vouches[member.id] = vouch_count
    await ctx.send(f"Congratulations! {member.mention} has been vouched {vouch_count} time(s).")

@bot.command()
async def vouchcheck(ctx, member: discord.Member = None):
    if member is None:
        await ctx.send("Hey! To use this feature, please mention a user. Example: `.vouchcheck @user`")
        return

    vouch_count = vouches.get(member.id, 0)
    await ctx.send(f"{member.mention} has {vouch_count} vouch(es).")

@vouch.error
async def vouch_error(ctx, error):
    if isinstance(error, commands.MemberNotFound):
        try:
            member_id = int(ctx.message.content.split()[1])
            member = bot.get_user(member_id)
            if member:
                await vouch(ctx, member)
            else:
                await ctx.send("Invalid user ID!")
        except ValueError:
            await ctx.send("Member not found or invalid user ID!")

bot.run('its here just not in the message')```
fast osprey
#

It's unclear what you want to do or where the problem is

coarse ridge
fast osprey
#

Your error handler is probably eating errors you don't expect

patent hull
#

And also, if you are making the member arg required, why do you pass None as default?

#

That way you're making that param optional...

#

And it raises commands.MissingRequiredArgument error if the param is not provided

#

So you can just catch that 🤷

#

And as Solstice said, your error handler probably eating errors

fast osprey
#

Bad error handling is worse than no error handling. At minimum, you should be logging every error you get, independently of how you respond to the users for some of them

slate swan
#

hi someone can give me a lookup discord account commande just with id bot in python pls ?

slate swan
simple prawn
#

why is my keyboard like this

upbeat otter
# slate swan like that

I have some old code for this ->

@app_commands.command(name="info", description="Get the info of a user")
    async def info(self, inter: discord.Interaction, user: discord.User | discord.Member=None) -> None:
        await inter.response.defer(ephemeral=True, thinking=True)
        user = user or inter.user
        
        embed = Embed(colour=user.top_role.colour).set_thumbnail(user.display_avatar.url)
        
        embed.add_field("Username", user, inline=True).add_field("Display name", user.global_name, inline=True).add_field("Discord ID", user.id).add_field("Status", user.status, inline=True).add_field("Avatar URL", f"[{user.name}'s avatar URL]({user.display_avatar.url})", inline=True)

        embed.add_field("Nickname", user.display_name, inline=True).add_field("Colour", user.top_role.colour, inline=True).add_field("Number of Roles", len(user.roles)-1, inline=True).add_field("Server join", generate_timestamp(user.joined_at), inline=True).add_field("Account created", generate_timestamp(user.created_at), inline=True) if isinstance(user, discord.Member) else ...
        
        embed.add_field("Activity", ", ".join([activity.name for activity in user.activities])) if user.activities else ...

        await inter.edit_original_response(embed=embed)

PLEASE DO NOT COPY PASTE IT

upbeat otter
hearty basalt
#

i have something similar:

@bot.command(name='userinfo')
async def userinfo(ctx, user: discord.Member = None):
    if user is None:
        user = ctx.author

    embed = discord.Embed(color=discord.Color.pink())
    embed.add_field(name="Nickname", value=user.mention, inline=False)
    embed.set_author(name=str(user), icon_url=user.avatar.url)
    
    obj = user.created_at # for account age
    obj_date = str(user.created_at)[:10] # for account join date
    current_date = datetime.now()
    
    age_years = current_date.year - obj.year
    age_months = current_date.month - obj.month
    
    if current_date.month < obj.month or (current_date.month == obj.month and current_date.day < obj.day):
        age_years -= 1
        age_months += 12
    if age_months < 0:        
        age_years -= 1
        age_months += 12
        
    age = f"{age_years} years, {age_months} months"
    embed.add_field(name='Account Age', value=f"{age}, ({obj_date})", inline=False)
    # if user doesnt have a custom server pfp use the user pfp
    if user.guild_avatar:
        thumbnail_url = user.guild_avatar.url
    else:
        thumbnail_url = user.avatar.url
    embed.set_thumbnail(url=thumbnail_url)

    join_date = str(user.joined_at)[:10]
    embed.add_field(name="Joined Server", value=join_date)
        
    roles = [role for role in user.roles if role.name != '@everyone']
    roles = sorted(roles, key=lambda x: x.position, reverse=True)
    max_roles = 25
    total_roles = len(roles)
    
    if total_roles > max_roles:
        roles = roles[:max_roles]

    role_mentions = [r.mention for r in roles]
    
    if role_mentions:
        role_string = ''
        for role_mention in role_mentions:
            if len(role_string) + len(role_mention) <= 1024:
                role_string += role_mention + ' '
            else:
                break

        if total_roles > max_roles:
            field_name = f"Roles [{total_roles}] (Showing first {max_roles})"
        else:
            field_name = f"Roles [{total_roles}]"
        embed.add_field(name=field_name, value=role_string.strip(), inline=False)

    embed.set_footer(text='ID: ' + str(user.id) + '  |  Made by vilkaviskietis')
    await ctx.send(embed=embed)
#

this is the output

hearty basalt
coarse ridge
# fast osprey Bad error handling is worse than no error handling. At minimum, you should be lo...

ty this worked although it let me vouch in every channel so i tried to fix it it responds in every channel except for the vouch one

from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.guild_messages = True
intents.members = True

bot = commands.Bot(command_prefix='.', intents=intents)

vouches = {}
scam_strikes = {}

# Define the ID of the specified channel
specified_channel_id = 1248953825541361758

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

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    # Check if the message was sent in the specified channel
    if message.channel.id == specified_channel_id:
        await bot.process_commands(message)

@bot.command()
async def vouch(ctx, member: discord.Member):
    vouch_count = vouches.get(member.id, 0)
    vouch_count += 1
    vouches[member.id] = vouch_count
    await ctx.send(f"Thank you for vouching {member.mention}!")

@bot.command()
async def vouchcheck(ctx, member: discord.Member):
    vouch_count = vouches.get(member.id, 0)
    scam_strikes_count = scam_strikes.get(member.id, 0)
    
    profile_embed = discord.Embed(title=f"〔✧〕╰──╮ {member.display_name} Profile╭──╯〔✧〕",
                                  description=f"Heres {member.display_name}'s profile page",
                                  color=discord.Color.blurple())
    profile_embed.add_field(name="Vouches", value=f"{vouch_count} vouch(es)")
    profile_embed.add_field(name="Scam Strikes", value=f"{scam_strikes_count} scam strike(s)")
    await ctx.send(embed=profile_embed)

@vouch.error
@vouchcheck.error
async def command_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("Please mention a user.")
    else:
        # Log the error for debugging purposes
        print(f"Error occurred: {error}")

bot.run('thingy')```
fast osprey
#

Is that a question? Confused if something isn't working with this

hearty basalt
coarse ridge
hearty basalt
#

bc once you restart the bot the vouches = {} will reset to an empty dictionary

#

atleast i think

fast osprey
#

You shouldn't use flat text files to store application data

fast osprey
#

Use a database if you want it to persist

hearty basalt
#

or just a json file