#discord-bots

1 messages · Page 381 of 1

limber jolt
#

ho-

fast osprey
#

Can you put all of bot.py in a paste service and send it? Removing any tokens

limber jolt
# fast osprey Can you put all of bot.py in a paste service and send it? Removing any tokens
from discord.ext import commands
import sqlite3
import cogs.input



conn = sqlite3.connect('shifts.db')
cursor = conn.cursor()


# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

    try:
        await bot.load_extension('cogs.shift')  
        await bot.load_extension('jishaku')
        await bot.load_extension('cogs.fun')
        await bot.load_extension('cogs.utility')
        await bot.load_extension('cogs.moderation')
        await bot.load_extension('cogs.input')
        print('Cogs loaded successfully')
    except Exception as e:
        print(f'Failed to load cog: {e}')
        print(cogs.input.__file__)
print(cogs.input.setup)

bot.run('Cant have my token (:')```
#

Its small

fast osprey
#

There's a few things that are major issues here. But no idea why it would think that module lives in bot.py

#

wait, that's not you actually printing the module file -_-

#

please put the debugging prints at the top of your file before you do anything else

limber jolt
fast osprey
#

Show your code, and show what you're getting

#

you should be printing the __file__ first

limber jolt
# fast osprey Show your code, and show what you're getting
from discord.ext import commands
import sqlite3
import cogs.input

print(cogs.input.__file__)
print(cogs.input.setup)



conn = sqlite3.connect('shifts.db')
cursor = conn.cursor()


# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

    try:
        await bot.load_extension('cogs.shift')  
        await bot.load_extension('jishaku')
        await bot.load_extension('cogs.fun')
        await bot.load_extension('cogs.utility')
        await bot.load_extension('cogs.moderation')
        await bot.load_extension('cogs.input')
        print('Cogs loaded successfully')
    except Exception as e:
        print(f'Failed to load cog: {e}')


bot.run('Token')


#

output:

#
c:\Users\willi\Desktop\Free_Novem_discord_bot\cogs\input.py
Traceback (most recent call last):
  File "c:\Users\willi\Desktop\Free_Novem_discord_bot\bot.py", line 7, in <module>
    print(cogs.input.setup)
          ^^^^^^^^^^^^^^^^
AttributeError: module 'cogs.input' has no attribute 'setup'
PS C:\Users\willi\Desktop\Free_Novem_discord_bot> ```
fast osprey
#

And if you go to that directory and file, does it have a setup method?

limber jolt
#

I put the code In It

fast osprey
#

Did you...not save the file

limber jolt
#

But clearly not

fast osprey
#

That'll definitely do it lol

limber jolt
#

Still get It

#

Has no setup function but It does

fast osprey
#

Error doesn't lie

wanton current
#

not with that attitude

limber jolt
trim oriole
#

using slash commands also need a bot like bot = discord.ext.commands.Bot(command_prefix=".", intents=intents)?

#

i mean am not using command_prefix or prefix commands

#

but still to make a Bot i need to give it

merry cliff
#

Yeah

sick birch
#

you need a CommandTree more than that

trim oriole
#

btw is this ok i am learning buttons i think i made a heads tails ```py
class HeadnTail(discord.ui.View):
def init(self):
super().init(timeout=None)
self.heads = True if random.choice(["heads","tails"]) == "heads" else False

@discord.ui.button(label="Heads",style=discord.ButtonStyle.red)
async def heads(self, interaction: Interaction, button: discord.Button):
    if self.heads:
        await interaction.response.send_message("Its head")
    else:
        await interaction.response.send_message("It was tails")

@discord.ui.button(label="Tails",style=discord.ButtonStyle.blurple)
async def tails(self, interaction: Interaction, button: discord.Button):
    if not self.heads:
        await interaction.response.send_message("Its tails")
    else:
        await interaction.response.send_message("It was heads")

@bot.tree.command(name="toss")
async def toss(interaction: Interaction):
await interaction.response.send_message(content="Choose heads or tails",view=HeadnTail())

fast osprey
#

Client supports app commands, you don't need ext.commands at all. You just would make your own CommandTree if you were using Client

slate swan
fast osprey
#

What's the output of py -m pip freeze?

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @slate swan until <t:1721391182:f> (10 minutes) (reason: newlines spam - sent 112 newlines).

The <@&831776746206265384> have been alerted for review.

wanton current
#

damn

coral flicker
#

!unmute @slate swan

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction timeout for @slate swan.

coral flicker
#

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

oh aigh

fast osprey
#

Yeah you've got a load of competing libraries

slate swan
#

how do ifix that

fast osprey
#

You should pick one discord library you want to work with, uninstall the rest, then reinstall that one

#

it's up to you which one you pick

slate swan
#

how do i do that

fast osprey
#

Which part

quick gust
#

you pip uninstall <lib> to uninstall a library

slate swan
#

i wold have to do it to alot of my libs

quick gust
#

add commas

slate swan
#

oh aigh

quick gust
#

but first decide which one u want to use

fast osprey
#

(preferably anything you do with python goes through py, i.e. py -m pip uninstall ...)

slate swan
slate swan
#

whats the discord librarys i have

quick gust
fast osprey
#

anything in that list which says discord

slate swan
#

ok

quick gust
slate swan
fast osprey
#

and then reinstall it with a 2.0+ version

slate swan
#

how do i reinstall with a specific version

fast osprey
#

Could just uninstall, then install it again

slate swan
#

after uninstalling other discord libs

quick gust
#

while installing the lib, specify the version with ==<version>. Or if u want the latest version you could do py -m pip install -U discord.py

slate swan
#

ok

fast osprey
#

(probably also using --force-reinstall)

slate swan
fast osprey
slate swan
#

py -m pip install -U discord.py --force-reinstall

fast osprey
#

Then you can't use the other libraries you were trying to use

#

you need to pick one library, and have your code use it

#

You got yourself into a state where you were picking from different libraries that are incompatible with each other. discord.py almost definitely supports whatever you're trying to do, but you have to use its syntax if you want to pick that one

slate swan
fast osprey
#

I will not be modifying your code for you, no

slate swan
#

ok

fast osprey
#

The changes should be fairly straightforward, but I haven't worked with all of these offshoot libraries to know how much they've diverged

slate swan
#

i fixed it, js had topy -m pip install discord_webhook

fast osprey
#

You should not be installing multiple discord libraries

#

This causes unforeseen instabilities in the future

slate swan
#

does any1 know a fix to this

twin cargo
#

hello guys, this is not an advertisment but i wanna make friends with someone who knows python for discord bots to help me develop my own bot. the idea of the bot is complicated but if everything goes alright there is a chance to make money, even lots of money. dm who is interested in this and also i have no one to speak with((((

slate swan
#

!rule tos

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.

slate swan
#

Boost bots are against Discord's ToS, and can easily get your bot and yourself banned

slate swan
slate swan
# slate swan

Read the message of @unkempt canyon above, you won't get help to violate the ToS of Discord

slate swan
#

Obviously, we're not dumb, you realize that

jaunty sparrow
#

Your screenshot literally says boost bot

dense falcon
#

lmfao 😭

slate swan
#

so many ppl habve them

dense falcon
#

what does a boost bot even do......

slate swan
#

boosts a server alot of times in a couple seconds i think

jaunty sparrow
#

Well, now you know. Also chill with the language, don't be rude to someone telling you about the rules

slate swan
#

Sorry

limber jolt
#

I stg pleaseh help me

#

Im still getting this error

#

HOLY

#

I FIXED IT

limber jolt
silk wolf
#

how you all have active developer badge

limber jolt
silk wolf
limber jolt
#

How do I make a slash command resister faster?

#

someoneee

fast osprey
#

What makes you think they aren't registered?

hearty basalt
#

what does resister mean

limber jolt
hearty basalt
#

reload your client

#

if you synced

limber jolt
fast osprey
#

not your code, your client

limber jolt
#
from cogs import cogs.input```
#

Cogs Is the folder and cogs.input is the name of the file as input is Python I put cogs.input as the filename

fast osprey
#

What's the question?

limber jolt
fast osprey
#

That's not how imports work

#

Also if you're loading this as an extension, you don't also need to import

limber jolt
fast osprey
midnight oracle
#

XD

limber jolt
fast osprey
#

Like an extension?

limber jolt
somber sky
#

https://paste.pythondiscord.com/SNCQ

Basically how the command is supposed to work is you run the command and insert all the stats, the stats transfer to a google sheetwith everything you put. Then if you run the command again and put a username that is already in the google sheet then it will update that persons stats and will add everything you put so for example if you had 5 touchdowns at first and then you do insert again with the same player and add 10 touchdowns then the player should have 15 touchdowns but heres the problem:

Every time I do /insert_qb_stats it works fine. But once I do it again with the same username meaning that it would update the stats, i have no clue why but all the data just messes up, like it passes on data to wrong stats or instead of adding on it just updates the number and idk why.

fast osprey
#

Are you trying to use a google sheet as a database?

somber sky
#

the database is cause i have other commands called /view_stats and /statleaders which shows stat leaders so basiccaly whenever I insert stats it makes a database for those commands but it goes straight to a google sheet that i defined at the top of my code

#

and im sure there might be an easier way of doing it but it works and its also not the problem the problem is the insertion from the command to the google sheet

fast osprey
#

There are better tools for tracking and storing data in your application. Namely databases

somber sky
#

im sure but im not rlly worried abt that rn im js mainly trying to figure out the google sheet problem and then ill move onto finding better ways to store data application wise

somber sky
craggy anvil
#

Hey how can i do this:

    async def confirmation_complete(self, channel):
        for msg in self.confirmation_messages:
            await msg.delete()
#

basically

#

it gives me error

await msg.delete()
      ^^^^^^^^^^

AttributeError: 'NoneType' object has no attribute 'delete'

#

ofc but what can i do instead to delete confirmation_messages

craggy anvil
slate swan
#

“Numpy is not avalible”

astral tiger
#

does anyone what this thing called?

#

I'm tyna search what this thing called, where it would display the add and remove

#

i already have the choice input just don't know how to add the display thingy where the user can see the two option of add and remove

limber jolt
#

I have a log_channel = {} but I need that to be used on more than 1 file. How would i do this?

#

As iN my bot.py I have a log channel command. And I need It to connect with other files so It can send message to that log channel.

limber jolt
#

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')


if __name__ == '__main__':
    app.run(debug=True)```
#

I get this page cant be reached when I go to the link It gives me

exotic hazel
limber jolt
#

Like a dashboard

exotic hazel
sudden birch
#

hello guys i have a problem to start my finished bot if anyone is free to help me just dm me 😆

blissful crane
quick gust
vocal laurel
limber jolt
#

Anyone know how to make a dashboard?

wanton current
#

do you know web development

trim oriole
#

class ConfirmButton(discord.ui.View):
    def __init__(self):
        self.joined = None
        super().__init__()

    @discord.ui.button(style=discord.ButtonStyle.green, label="Confirm", emoji="🆗")
    async def confirm(self, interaction: Interaction, button: discord.ui.Button):
        self.joined = True
        await interaction.response.send_message(
            ephemeral=True, content="Confirmed Your Place"
        )

    @discord.ui.button(style=discord.ButtonStyle.red, label="Cancel", emoji="❌")
    async def cancel(self, interaction: Interaction, button: discord.ui.Button):
        self.joined = False
        await interaction.response.send_message(
            ephemeral=True, content="Cancelled YOur place"
        )

@bot.tree.command(name="comp",description="JOin a COmpi")
async def compi(interaction: Interaction):
    await interaction.response.send_message("Welcome",view=ConfirmButton())
```  is this correct way of making button
#

now i want the buttons to disappear after user submits

fast osprey
#

You can respond instead with edit_message to edit the message the buttons are on. Passing view=None would remove the buttons

limber jolt
neon olive
#

Guys can anyone suggest me some library's for create a good discord bot ? I want to create discord bot but I only heard about discord.py is there any better library's for that or ?

fast osprey
#

This is pretty subjective. What is it you believe about discord.py to be lacking?

still briar
#

m

amber moth
#
@bot.tree.command(name='command')

Is this a correct way of creating slash commands?

My code is working without any errors but the bot is still not having slash commands

fast osprey
#

Did you sync them?

drowsy thunder
fast osprey
#

You really should not be using on_ready, especially not for things that are heavily rate limited like this

finite salmon
drowsy thunder
#

That's alot of code to read ngl.
Also I need the function of your code too

fast osprey
#

There already exists a way of giving roles to people. You don't need a bot to do it, and if anything this is just reducing auditing and security

finite salmon
#

why are you using the on_message event instead of making it into a command

#

commands handle argument parsing for you

#

it doesnt have to do anything with replit

#

and dont use replit for discord bots whatsoever

#

use an actual code editor / ide for coding and buy a vps for hosting it

fast osprey
#

You can right click on members and add roles from that

craggy anvil
#

bro i cant believe this, it just stopped working for no reason i will kms

#

and my error when i send user id or username of guy i want to deal with:

An error occurred: list index out of range

flint nexus
craggy anvil
#

it worked like few hours ago

craggy anvil
#

Thanks for trying to help tho blobthumbsup

mild token
#

Anyone have added application emoji and used using d.py?

vocal laurel
#

its the same as a normal emoji according to danny

trim oriole
#

what should i use to make slash commands and interaction UI in discord.py extend discord.Client with CommandTree or use discord.ext.command.Bot

golden portal
#

commands.Bot if you plan to use cogs

marsh schooner
#

hey anyone

#

online here

tight obsidian
sick birch
#

if so, use bot

#

if you're 100% sure you're never going to add text commands you can simply use client with an attached command tree

trim oriole
#

i may need somecommand also ig

#

i go with Bot

sick birch
#

sure

limber jolt
#

Can someone give me dashboard src?

slate swan
slate swan
#

What kind of question is that? Just try it and see

#

There's no partner thing anymore, so it's pretty simple

#

And vertification is currently stopped, since some years - so yeah

#

And common sense would tell you that you can't verify a server called "Discord" as it's the perfect scam

snow coral
#

How do I change a roles color and icon? Couldn’t find it in the docs

fast osprey
#

!d discord.Role.edit

unkempt canyonBOT
#

await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the role.

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

All fields are optional.

Changed in version 1\.4: Can now pass `int` to `colour` keyword\-only parameter.

Changed in version 2\.0: Edits are no longer in\-place, the newly edited role is returned instead...
turbid condor
#

wasn't that hard to search imo

amber moth
#
@bot.tree.command(name='buy')
async def buy(interaction: discord.Interaction, service_name: str, link: str):
    services = load_services()

How do i make options for service_name instead of having to write the name

fast osprey
#

Is the set of options static or some kind of lookup?

amber moth
#

static

fast osprey
#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
amber moth
#

Oh but i when i do this the slash command doesn't appear on discord anymore

fast osprey
#

Code? And how are you syncing them?

amber moth
#
@bot.event
async def on_ready():
    print(f'تم تسجيل الدخول باسم {bot.user}')
    
    await bot.tree.sync()
    print("Commands synced with Discord.")

bot.run('YOUR_BOT_TOKEN')
#
@app_commands.command(name='buy', description='Purchase a service.')
    @app_commands.describe(service_name='The name of the service to buy', link='URL of the service')
    @app_commands.choices(service_name=[
        app_commands.Choice(name='hi', value='eeee'),

I have more options btw

fast osprey
#

What's the signature of the command method?

#

Also you should remove your syncing from on_ready asap or you're going to rapidly rate limit yourself out of developing

fast osprey
#

on_ready fires repeatedly and randomly, and is almost never the answer for something most people are trying to do

amber moth
#

is it the correct way to sync my command anyways?

#

Why my slash command disappears when i make it with options but when i do it like that

@bot.tree.command(name='buy')
async def buy(interaction: discord.Interaction, service_name: str, link: str):
    services = load_services()

It works

fast osprey
#

It is not

#

on_ready fires randomly and repeatedly. You do not want to sync randomly and repeatedly. Hence, it is not appropriate

amber moth
#

Should i give you my code

fast osprey
slate swan
#

anybody know which is harder to code bots in? py or js?

fast osprey
#

Varies entirely person to person, it's very subjective

slate swan
#

Someone who never touched js: js
Someone who never touched py: py
Someone who never touched js and py: Depends what they want to learn, if you learn you'll know it and then it won't be hard, doesn't matter the language

vague junco
#
def EULAConfirmation():
    os.system("cls")
    print("Agree licence plz \n\n1. Accept\n2. Disagree\n3. Read license\n0. Exit")

    while True:
        try:
            user_input = int(msvcrt.getch().decode())
            break
        except ValueError:
            pass

    if user_input == 1:
        return run_bot_and_check_token_valid()
    elif user_input == 2:
        return "Bad opinion (Licence is magndatory to confirm)"
    elif user_input == 3:
        webbrowser.open("...", new=0)
        return EULAConfirmation()
    elif user_input == 0:
        return 0
    else:
        return EULAConfirmation()

Is there a way to completely remove the ability to type not only characters but also other numbers besides 1, 2, 3, 0?

slate swan
vague junco
slate swan
#

Your question has nothing to do with discord bots, it's basic Python stuff

vague junco
slate swan
#

It may be part of a discord bot project, but the queso is completely unrelated to discord bots

dense falcon
#

This is more of just a server-related question, but if I run a bot on a server via ssh, is it possible for me to quit this ssh session without stopping the process?

wild gate
#

client = commands.Bot(command_prefix='!', intents=nextcord.Intents.all(), help_commad=None)
can i add the help_command = None so that I can customize my own help command?

sick birch
sick birch
#

You should pass in your own subclass instead

willow sluice
#

hi guys
i have such code inside my view class. add_buttons is a preparing function that is called inside __init__ and adds pagination buttons. and i also have close button created using @button decorator.
my problem is a close button position under message. i want it to be last one now its first. how can i do this?
https://media.discordapp.net/attachments/1256678894245777484/1264721806128971889/image.png?ex=669ee777&is=669d95f7&hm=aef96fc2f3442291ed83a43e00ac60ee25cb9c255c26590965903fc367a23212

    def add_buttons(self):
        self.add_item(PaginationButton(pagination_step=-5, custom_id='prev_pages', emoji=':prev_pages:'))
        self.add_item(PaginationButton(pagination_step=-1, custom_id='prev_page', emoji=':prev_page:'))
        self.add_item(PaginationButton(pagination_step=1, custom_id='next_page', emoji=':next_page:'))
        self.add_item(PaginationButton(pagination_step=5, custom_id='next_pages', emoji=':next_pages:'))

    @discord.ui.button(emoji=':close_x:', style=discord.ButtonStyle.danger)
    async def close_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.message.delete()
fast osprey
#

You probably don't want to mix and match add_item with the @ui.button decorator

willow sluice
# fast osprey You probably don't want to mix and match add_item with the `@ui.button` decorato...

i also tried this way to add close button but that doesnt work either. when i click on button callback is called but message with view isnt deleted. can you recommend another solution for what i want to do?

    def add_buttons(self):
        self.add_item(PaginationButton(...))
        self.add_item(PaginationButton(...))
        self.add_item(PaginationButton(...))
        self.add_item(PaginationButton(...))

        close_btn = discord.ui.Button(...)
        close_btn.callback = self.close_button_callback
        self.add_item(close_btn)

    async def close_button_callback(self, interaction: discord.Interaction):
        await interaction.message.delete()
timber dragon
#

But you can remove and add them in the order you want to

#

Definitely don't monkeypatch

timber dragon
willow sluice
#

what is self.close_button? can you show example how should i do it

willow sluice
fast osprey
#

You are already making buttons without monkeypatching

willow sluice
fast osprey
#

Yes

#

You're adding 5 buttons. One of them monkeypatches. The other 4 don't

willow sluice
#

but i dont want to create new button class that will implement discord.ui.Button for only 1 button

fast osprey
#

That is purely your own preconception

#

Classes don't cost you anything

spiral kiln
#

Is there a better way to write line 26?

import os
from dotenv import load_dotenv
import discord
import ollama

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

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

client = discord.Client(intents=intents)


@client.event
async def on_ready():
    print(f'Logged in as {client.user}')


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


    if message.content.startswith('jeb ') or message.content.startswith('Jeb') or message.content.startswith('JEB') or message.content.startswith('jim') or message.content.startswith('Jim') or message.content.startswith('jebot') or message.content.startswith('JEBot'):
        print("full message = " + message.content)
        
        User_LLM_Input = message.content.replace('jeb ', '')
        print("LLM input = " + User_LLM_Input)
        
        LLM_Output = ollama.chat(model='gemma:2b', messages=[
          {
            'role': 'user',
            'content': User_LLM_Input,
           },
         ])

        print(LLM_Output)
        await message.channel.send(LLM_Output['message']['content'])


client.run(TOKEN)
#

Oops here is line 26

    if message.content.startswith('jeb ') or message.content.startswith('Jeb') or message.content.startswith('JEB') or message.content.startswith('jim') or message.content.startswith('Jim') or message.content.startswith('jebot') or message.content.startswith('JEBot'):
willow sluice
# timber dragon ```py self.clear_items() ... self.add_item(self.close_button) self.add_item(...)...

i understood that by self.close_button you meant function to which decorator was applied. thank you its working now

    def add_buttons(self):
        self.clear_items()
        self.add_item(PaginationButton(...))
        self.add_item(PaginationButton(...))
        self.add_item(PaginationButton(...))
        self.add_item(PaginationButton(...))
        self.add_item(self.close_button)

    @discord.ui.button(...)
    async def close_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.message.delete()
willow sluice
willow sluice
spiral kiln
willow sluice
#

ask chatgpt https://chatgpt.com/ or google it. there is really lot of examples how to make your own command

#

you can also set several prefixes for your bot or aliases for command

golden portal
#

it also support multiple prefixes

spiral kiln
#

i think this is fine for now

#

I do have another question though, how do i make it show the thing that appears when another user is typing while the LLM is generating?

trim oriole
#
@bot.tree.command(name="bm",description="bookmarks the content")
async def add_bookmark(interaction: discord.Interaction, bookmarklink: str):
    with open("bookmarks.json",mode="r",encoding="utf-8") as bookmark_store:
        bookmark = json.load(bookmark_store)
        user = interaction.user
        user = str(user)
        print(user,bookmark)
        if user not in bookmark:
            bookmark[user] = []
    with open("bookmarks.json",mode="r+",encoding="utf-8") as bookmark_store:
        bookmark[user].append(bookmarklink)
        json.dump(bookmark,bookmark_store)
        await interaction.response.send_message("Bookmark saved")``` is this ok for a bookmark feature .. now i already created a json file with {}  present in it .. is this approach good?
barren forum
#

how to set bot status like , playing game , watching

sacred vigil
sacred vigil
#

found this

# Setting `Playing ` status
await bot.change_presence(activity=discord.Game(name="a game"))

# Setting `Streaming ` status
await bot.change_presence(activity=discord.Streaming(name="My Stream", url=my_twitch_url))

# Setting `Listening ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="a song"))

# Setting `Watching ` status
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="a movie"))```
barren forum
sacred vigil
#

hm

barren forum
#

so do you have any idea , what should i do now

sacred vigil
#

that works for me

barren forum
sacred vigil
#

@barren forum

barren forum
#

let's see

sacred vigil
trim oriole
sacred vigil
#

would prob be like options/choices for the add,view,delete ig

stone gate
#

before defining your commands, you need to define the group

#

for example, your group would be

#

bm

trim oriole
trim oriole
stone gate
#

so literally you'd do bm = discord.app_commands.Group(name="bm", description="bookmark commands")

trim oriole
#

there isnt bot.tree.group

stone gate
#

then you do

#

@bm.command(name="add", description="adds a bookmark") for ur command

#

this is how its set up in my cog

trim oriole
# stone gate so literally you'd do `bm = discord.app_commands.Group(name="bm", description="b...

this return a Group but like this my whole code ```py
class Bot(discord.ext.commands.Bot):
def init(self):
intents = discord.Intents.all()
super().init(
intents=intents, command_prefix=discord.ext.commands.when_mentioned
)

async def on_ready(self):
    print("running")
    await self.tree.sync()

bot = Bot()

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

@bot.tree.command(name="bm",description="bookmarks the content")
async def add_bookmark(interaction: discord.Interaction, bookmarklink: str):
with open("bookmarks.json",mode="r",encoding="utf-8") as bookmark_store:
bookmark = json.load(bookmark_store)
user = interaction.user
user = str(user)
print(user,bookmark)
if user not in bookmark:
bookmark[user] = []
with open("bookmarks.json",mode="r+",encoding="utf-8") as bookmark_store:
bookmark[user].append(bookmarklink)
json.dump(bookmark,bookmark_store)
await interaction.response.send_message("Bookmark saved")

@bot.group(name="mygroup")
async def bot_grp(interaction: discord.Interaction):
pass
bot.run(token)``` i am not using app_commands

#

ignore last line

stone gate
#

I think its

#

@bot.group

trim oriole
#

but now bot_grp.tree doesnt work

stone gate
#

ah

trim oriole
#

is there someplace where i can really understand this library i just started yesterday

sacred vigil
trim oriole
#

yea im looking docs but still like too many ways to do things

jaunty cape
#

uh first of all, don't sync on_ready

#

that's all i have to say

#

goodbye 👋

trim oriole
#

so i should not use discord.ext.commands.Bot?

#

and use app_commands instead?

jaunty cape
#

no that's not what i'm saying, i'm saying don't sync in the function on_ready

#

okay bye 👋

trim oriole
#

in thier examples

jaunty cape
#

when you sync on_ready you sync every time you run your python program, you'll get ratelimited really quickly

trim oriole
#

ohh

stone gate
#

never used tree commands

jaunty cape
#

as far as i know they're the exact same

stone gate
trim oriole
#

okh ill look app_commands then.. but thier examples is full of tree commands

stone gate
#
from discord.ext import commands
import discord.utils

intents = discord.Intents.default()
intents.members = True
intents.typing = True
intents.presences = True
intents.message_content = True

client = commands.Bot(command_prefix='!', intents=intents)

@client.tree.error
async def on_app_error(interaction, error):
    if isinstance(error, discord.app_commands.MissingAnyRole):
        response = discord.Embed(title="Error", color=0xf54242)
        response.add_field(name="", value="You dont have perms for this!", inline=True)
        response.set_footer(text="PTV")
        await interaction.response.send_message(embed=response)
    else:
        raise error

@client.command()
async def sync(ctx):
    synced = await client.tree.sync()
    print(synced)

@client.event
async def setup_hook():
    # await client.load_extension("commands.user")
    # await client.load_extension("commands.clock")
    await client.load_extension("commands.admin")


@client.event
async def on_ready():
    print('The bot is on!')

client.run('YOUR TOKEN')  ```
#

i use cogs to be more organized, its really helpful

jaunty cape
#

woah why do you need every privileged intent

stone gate
#

since its for my server specifically I dont care, its easer since I have ADHD and might forget to add them when needed

jaunty cape
#
@bot.event
async def setup_hook() -> None:
    global keep_moving
    keep_moving = False
    await setup_database()
    print(await set_current_group_id())
    while not current_group_id:
        r_db.start(
            current_group_id
        ) if not r_db.is_running() and current_group_id else None
        db_online_loop.start(
            current_group_id
        ) if not db_online_loop.is_running() and current_group_id else None
    await load_cogs(bot)

async def load_cogs(bot: Bot, directory: Optional[str] = "cogs"):
    for filename in os.listdir(directory):
        if filename.endswith(".py"):
            cog: str = f"{directory}.{filename[:-3]}"
            try:
                await bot.load_extension(cog)
                print(f"Loaded extension: {cog}")
            except Exception as e:
                print(f"Failed to load extension {cog}: {e}")
#

i like to dynamically load cogs

#

it looks like you only have two cogs so you don't need to do that

stone gate
#

I have like 6-7, but i just deleted them in the one i sent for simplicity

jaunty cape
stone gate
#

ah it is

#

but like, its reading from the same level as the bot.py file right?

jaunty cape
#

this code is from my main.py program, cogs (dir) is in the same directory yes

stone gate
#

the thing is, specially with testing, its easier for me to disable every cog i dont neet in that moment

#

just comment it out and thats it

jaunty cape
#

i see

stone gate
#

but that looks super cool though!

jaunty cape
#

in my case, i need every Cog to be loaded at the same time

jaunty cape
#

because well

#

idk i just need the commands to be loaded

stone gate
#

lmao, fair

#

guess its useful if you're setting up multiple cogs and you change things constantly

#

mind if i test it in my bot?

jaunty cape
#

no i don't mind, i really don't care if you took some code from me

#

smh i'm really bad at english

stone gate
#

dw, me too

trim oriole
stone gate
jaunty cape
#

basic structure of a Cog with no commands

#

actually if you use the default discord help command, that docstring gets added as a description of the Cog

barren forum
#

why my bot status is not showing ?

fast osprey
#

You should not be using on_ready for this. It fires repeatedly and randomly. You can pass initial presence into the bot constructor instead

jaunty cape
#

can i make a command both a context menu command and a slash command?

fast osprey
#

Given that they support disjoint parameters it's unclear how that would even work

#

Unless you're trying to make a slash command that accepts a member

jaunty cape
#

i just made two separate commands

#

it's a solution i guess

jaunty cape
fast osprey
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, ...)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2\.0\.
fast osprey
#

You can pass activity and status in when creating your bot

jaunty cape
#

^ no idea what this guy is trying to say

barren forum
dusky pine
#

do you not know how to pass in arguments to constructors

jaunty cape
#

I’m not, I just don’t know what that guy is trying to say

jaunty cape
dusky pine
#

😂

fast osprey
#

I mean. You could ask a targeted question

timber dragon
#

Let's explain it in baby language:

❌ VERY BAD:

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

@bot.event
async def on_ready():
    await ...change_presences(activity=..., status=...)

# discord:
on_ready()
.. # after 5 secs
on_ready()
# maybe discord: why tf are you changing presences here, fuck off, <bot dies>
on_ready()
... # after 3 hours
on_ready()
..
on_ready()
on_ready()
# maybe discord: why tf are you changing presences here, fuck off, <bot dies>
on_ready()
...

✅ VERY GOOD:

bot = commands.Bot(
    command_prefix=...,
    intents=...,
    activity=...,
    status=...
)

# discord: oh you want the startup activity to be x and status y? That's easy!
lucid ember
#
for msg in channel.history(limit=5000):

Any idea why this prints as not iterable?

fast osprey
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.

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

Examples

Usage...
fast osprey
#

There's a usage example in there

robust fulcrum
#

guys how can we get current time of the user calling the command?

robust fulcrum
#

nvm i found

timber dragon
#

There is Interaction.locale

#

Oh? What did you find

robust fulcrum
#
inter.created_at
timber dragon
#

That's the time the interaction was created it in utc

#

Not at all connected to the user lol

robust fulcrum
#

isn't that the time of interaction created by user?

timber dragon
#

Discord creates and sends interactions

junior falcon
#

hey there, is just 1vCore to low for a discord bot with a ticket feature and little other features?

dusky pine
#

but really it depends on the scale of your bot

#

if it's being used by a lot of users concurrently, consider scaling up

fast osprey
#

The only way to reasonably answer this remotely accurately is to run your thing and profile it

slate swan
#

How do i fix Numpy is not avalible

golden portal
junior falcon
dusky pine
junior falcon
hot stump
#

in discord.py:
i have a dropdown class:

class Shape_dropdown(discord.ui.Select):
  def __init__(self):
    ...
  async def callback(self, interaction: discord.Interaction):
      if not str(interaction.user.id) in self.custom_id:
        #what should i do here?
      else:
        #do stuff

now i want the dropdown to not update if the user is not permitted (the allowed user are in the custom id). how can i do it?
i didn't even find a way to see what was previously selected

fast osprey
#

You can do whatever other response you'd want

#

just defer, send a message, etc

hot stump
fast osprey
#

It doesn't though

hot stump
#

i want to to disable it, how can i do it?

fast osprey
#

They are not

#

discord.py does not make discord api calls (generally) behind your back, and not in this case

#

What you implement in the callback is what happens. If you implement nothing, nothing happens

hot stump
# fast osprey It doesn't though

you're right......,this is what i found out:

if u select something on select dropdown, discord client will show it as selected even if the bot did not update the dropdown

u can see in the left is where i triggered the command, and in the right i tried to change the selected color, and it does update there. a simple reload to the right side resets it

fast osprey
dry kelp
#

Hello

#

Discord has added emojis built in bot, But i am having trouble using them.

#

Using them as normal emojis, What's wrong?

#

Ah apologies, i forgot the :

timber dragon
#

The name isn't important fwiw
<:_:ID> works everywhere

spiral kiln
#

im trying to make my bot reply to a message instead of message.channel.send anyone know how?

spiral kiln
#

yeah

dry kelp
dry kelp
spiral kiln
# dry kelp That should reply to the message
2024-07-22 09:45:25 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/caleb/python-projects/bot/.venv/lib64/python3.11/site-packages/discord/client.py", line 449, in _run_event
    await coro(*args, **kwargs)
  File "/home/caleb/python-projects/bot/main.py", line 51, in on_message
    await message.channel.reply(LLM_Output['message']['content'])
          ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'TextChannel' object has no attribute 'reply'
dry kelp
#

Could you send a snippet of your code?

spiral kiln
#
await message.channel.reply(LLM_Output['message']['content'])
        print('output: ' + (LLM_Output['message']['content']))
dry kelp
#

I mean for reply, sorry im on phone

#

You can only reply to a message, you are replying to a channel

spiral kiln
#

oh ok

#

makes sense

dry kelp
#

You need to ensure the channel you want, and reply to the expected message

spiral kiln
#

so message.channel.______

#

then .reply

dry kelp
#

What i mean in your code you should have a function that defines the channel you want.

if not channel.id == `channel id here`:
  return

This will check for the channel you want, and ensure all the actions happen in the mentioned channel.

spiral kiln
#

seems to work thanks

#

:D

dry kelp
spiral kiln
#

One more thing i need help with, you know how when someone types it says they're typing? How can i make that appear while the LLM is generating?

dry kelp
#

Ah that's simple.

upbeat otter
#

!d discord.ext.commands.Context.typing

unkempt canyonBOT
#

async with typing(*, ephemeral=False)```
Returns an asynchronous context manager that allows you to send a typing indicator to the destination for an indefinite period of time, or 10 seconds if the context manager is called using `await`.

In an interaction based context, this is equivalent to a [`defer()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context.defer) call and does not do any typing calls.

Example Usage:

```py
async with channel.typing():
    # simulate something heavy
    await asyncio.sleep(20)

await channel.send('Done!')
```...
dry kelp
#

For example you can do

async with ctx.typing():
  await asyncio sleep(5)

  await ctx.send("here's your response")
dry kelp
upbeat otter
#

lol

#

sori

dry kelp
upbeat otter
#

😔

dry kelp
spiral kiln
#

uhh its a message.content.lower().startswith i know its not the best

#

lol

dry kelp
#

I just would like to see the command parameters.

spiral kiln
#
    if message.content.lower().startswith('jim'):
``` Its called jim as part of an inside joke.
dry kelp
remote thistle
#

what are the things I should check/do before releasing the bot?

spiral kiln
dry kelp
#

It should if im not mistaken

spiral kiln
#

i still dont understand async/await lol

#

or even with

civic reef
#

Is there a discord bot active currently which sends telegram channel msg to the discord server channel?

Active bot? Code is available on internet but I can't host it.

spiral kiln
civic reef
#

correct me if that bot is not this

spiral kiln
#

oh sorry

civic reef
#

np, chill

primal pilot
#

I'm trying to update the image inside an embed, that's inside a discord.View, but there's no file argument in the edit_message function

#

This is how the embed is originally created

#

Is it just not possible to update the image inside an embed, or is there some other way of doing this?

fast osprey
#

Check the parameters on InteractionResponse.edit_message

primal pilot
#

There is no file parameter. Would there be some way to do this with attachments?

fast osprey
#

That is the list of attachments that will be on the message after the edit. It accepts existing Attachments or new Files

primal pilot
#

Woah, it works now. I thought I tried that before, but maybe I did something wrong last time

#

Thanks!!

somber sky
#
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.

    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.

    If you wish to install a non-Debian packaged Python application,
    it may be easiest to use pipx install xyz, which will manage a
    virtual environment for you. Make sure you have pipx installed.

    See /usr/share/doc/python3.11/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.```

everytime i do `pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib` it gives me this error. Its only in command prompt tho when i do it in vscode it works fine.
#
apt install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
E: Unable to locate package google-api-python-client
E: Unable to locate package google-auth-httplib2
E: Unable to locate package google-auth-oauthlib```

and thats what happens if i try apt like it told me to
wanton current
#

did you try creating a venv?

somber sky
#

nvm i fixed it

jaunty cape
somber sky
robust fulcrum
#

Guys how can I get user's current time when the interaction takes place?

#

I wana get messages past x hours in a channel based on users time

jaunty cape
#

Hey people

#

Should I store my bot token in a .env or is toml just fine

sacred vigil
jaunty cape
#

I mean it should be okay to just use a toml file in this case right

hushed galleon
#

ive been using my config.toml for the token too, but either way you'd want to configure the file's permissions

dry kelp
#

Hello, is it possible to reply to a message with a webhook?

#

For example we put the message id as a paremeter of the command, And possibly replying to the message with a webhook.

jaunty cape
#

webhooks send messages. they're boring and can't do anything

mild token
#

How I can make this command?

#

And what it's called?

golden portal
#

context menu*

#

!d discord.app_commands.CommandTree.context_menu

unkempt canyonBOT
#

@context_menu(*, name=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command context menu from a regular function directly under this tree.

This function must have a signature of [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) as its first parameter and taking either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member), [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User), or [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message), or a [`typing.Union`](https://docs.python.org/3/library/typing.html#typing.Union) of `Member` and `User` as its second parameter.

Examples...
mild token
#

Is there a way to know with which invite link user joined the server?

mild token
#

Mainly i want to get the user object

finite salmon
#

But in some cases it won't work though

mild token
#

: ( not reliable then

finite salmon
#

But discord alr provides this feature in the app itself

#

So it's just reinventing the wheel in a worser way

mild token
#

Actually we need that for an event

#

We are hosting an event in which people who invite more will get something

#

So we need to maintain leaderboard

#

But the problem we are facing if someone left then discord invite count doesn't decreases

#

So we don't know exactly how many people stayed

finite salmon
#

You'll have to keep track of the members the user invites

mild token
#

Hmm

finite salmon
#

Just append it to a list or smt

mild token
#

I have to use db ig

#

Just list won't help

finite salmon
#

Well yea

robust fulcrum
#

Guys does interaction created_at tells time based on discord server or user's timezone?

foggy laurel
#

ah i have found my favorite channel on this server

#

what libs are yall using?

foggy laurel
robust fulcrum
#

thats not my question?

thin raft
unkempt canyonBOT
thin raft
#

maybe discord.dev has more info

#

cant find it

#

you could just do a test and change your computer date

#

and see if it changed

robust fulcrum
thin raft
fast osprey
#

In general, discord is not going to tell you where a user lives

robust fulcrum
#

so i need to get the local time of a user

thin raft
#

it doesnt matter the time of the user for that

robust fulcrum
#

so how do i get messges past 3 hours when the command ran?

thin raft
#

just use your datetime

robust fulcrum
thin raft
#

their messages are shown in your time

#

so -3 hours would still work because it would be the same offset

robust fulcrum
#

can you give one example?

thin raft
#

which hour do my messages appear to you?

robust fulcrum
thin raft
#

its 1.49pm for me

robust fulcrum
#

oh , so what do you wana tell me through this?

thin raft
#

so basically if you fetch my last 3 hours of messages

#

it will always fetch from now

robust fulcrum
#

how do i fetch last 3 hours of messages? thats my question

thin raft
#

async for channel.history() i think

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.

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

Examples

Usage...
robust fulcrum
#

ik but it would return all messages

thin raft
#

add an if

#

and check for author

robust fulcrum
#

i mean where do i tell it to get only past three hours?

thin raft
#

you can use after=

#

and set to now - 3 hours

robust fulcrum
#

kk, imma try

thin raft
#
offset = datetime.datetime.now() - datetime.timedelta(hours=3)
async for message in channel.history(after=offset):
  if message.author.id != 123123123:
    continue

   # DO STUFF WITH MESSAGE
#

that should work

opal vortex
#

speaking of which this is one of my discord bots.

south spire
# opal vortex

lemme find my message with more details (from a few years ago) and i'll tell you more about the RAM usage

opal vortex
#

oki

south spire
#

oki so i can't share the code because it's not mine to share (will ask the person who made it), but basically if you monkey patch discord.py to prevent it from storing voice/category channels as well as make it drop channel overwrite objects, you can save a lot of RAM

#

here's a rough amount of memory in KB used post-patching, it was significantly more before

craggy anvil
#

Hey if i have 2 files in one is class that sends embed asking for deal amount in $ and then when user gives number it sends new embed with buttons (that class is in another file) and it asks if correct or incorrect, now i wanna code if it's incorrect to reset proccess and come back to first embed that asked for amount and to listen again for number

south spire
south spire
craggy anvil
#

okay here is code

#

i want it to coem back to first class if button incorrect is clicked

hollow ice
opal vortex
opal vortex
#

just ignore it in the image

opal vortex
wet hill
opal vortex
#

since both of my bots don’t have voice support

wet hill
#

refer it

south spire
quick gust
blissful badge
#

Having a bit of trouble with using buttons, think maybe some of the language changed around these but having trouble making sense of the documentation. Trying to send a message with buttons but I keep getting this error

    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Button.__init__() got an unexpected keyword argument 'style'```

This is the code I am using for the specific extension

```py
import discord
import datetime
from discord.ext import commands
from discord import Button, ButtonStyle

class Joinverification(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = self.bot.get_channel(1230669525645660180)
        await channel.send(
            f"Welcome {member.mention} to the server! What would you like to do?",
            components=[
                [
                    Button(style=ButtonStyle.green, label="Option 1"),
                    Button(style=ButtonStyle.blue, label="Option 2"),
                    Button(style=ButtonStyle.red, label="Option 3"),
                ]
            ]
        )

    @commands.Cog.listener()
    async def on_button_click(interaction):
        member = interaction.author
        if interaction.component.label == "Just Visiting":
            await interaction.send("You clicked Option 1!")
        elif interaction.component.label == "Member of an allied org":
            await interaction.send("You clicked Option 1!")
        elif interaction.component.label == "Option 3":
            await interaction.send("You clicked Option 1!")

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

Any assistance would be MAJORLY appreciated

fast osprey
#

Which library are you using?

blissful badge
fast osprey
#

Which discord library? Like what you're installing through pip

fast osprey
#

2.4.0 of what library?

blissful badge
#

Sorry, I'm bad at reading into questions

fast osprey
#

and isn't in its docs

blissful badge
#

Oh, well that explains why I was having trouble

#

Alternate library you would recommend?

fast osprey
#

I would personally recommend doing discord.py's way of doing buttons, which is with View classes

#

it does support it, just not in this way (which imo is much hackier)

blissful badge
#

Ok got it, the view classes was what I was finding and struggling with. That just requires defining the view before the command and whatnot yeah?

fast osprey
#

Well you could define it anywhere you could define a normal python class

#

then just instantiate it and send it in your command

blissful badge
#

Got it, ok I will work on going that direction. Thank you VERY much Solstice!

fast osprey
#

prettythumbsup any time. The examples in the repo are quite extensive

blissful badge
blissful badge
#

Or would I be better off defining it after the cog/extension has been defined

blissful badge
#

Think I have the button part figured out, just using some of the example code in the repo to see if its working but.....the message simply isn't sending....feel like I am missing something obvious

import discord
from discord.ext import commands
from discord import Button, ButtonStyle

class joinverification(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel = await self.bot.try_channel(978421363884818472)
        view = Buttons()
        await channel.send(f"Welcome to the server! {member.mention}", view=view)

class Buttons(discord.ui.View):
    def __init__(self, *, timeout=180):
        super().__init__(timeout=timeout)
    @discord.ui.button(label="Blurple Button",style=discord.ButtonStyle.blurple) # or .primary
    async def blurple_button(self,button:discord.ui.Button,interaction:discord.Interaction):
        button.disabled=True
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label="Gray Button",style=discord.ButtonStyle.gray) # or .secondary/.grey
    async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
        button.disabled=True
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label="Green Button",style=discord.ButtonStyle.green) # or .success
    async def green_button(self,button:discord.ui.Button,interaction:discord.Interaction):
        button.disabled=True
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label="Red Button",style=discord.ButtonStyle.red) # or .danger
    async def red_button(self,button:discord.ui.Button,interaction:discord.Interaction):
        button.disabled=True
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label="Change All",style=discord.ButtonStyle.success)
    async def color_changing_button(self,child:discord.ui.Button,interaction:discord.Interaction):
        for child in self.children:
            child.disabled=True
        await interaction.response.edit_message(view=self)

async def setup(bot):
    await bot.add_cog(joinverification(bot))```
foggy laurel
#

Question for opinions

Would you all rather:

  • Enter 4 channelnames into a slash command and get 4 channels created outside any categories
    OR
  • Enter one category name and get the category with default channelnames

NOTE: all channels belong to the same feature
of course either way setup with the configured permissions

blissful badge
blissful badge
#

thats the obvious thing I was missing

#

it should be get channel

fast osprey
#

That should error though

blissful badge
#

Yeah not throwing any errors, still not throwing any errors with the get channel correction

#

Super weird

fast osprey
#

Are you logging anything at all?

blissful badge
#

Not a thing

fast osprey
#

You probably aren't enabling logging. How are you starting the bot?

blissful badge
#

py __main__.py

fast osprey
#

In code, how do you make the bot object and then start/run it?

blissful badge
#
def main() -> None:
    DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
    if not DISCORD_TOKEN:
        raise InvalidTokenException("A Discord token was not set.")

    with open("config.toml", "rb") as config_file:
        config = Config(tomllib.load(config_file))

    bot = Bot(config)
    bot.run(DISCORD_TOKEN)
#

Hope that is what you mean

fast osprey
#

Yeah. Hm. That should cause logging

#

do you get nothing at all in your terminal?

blissful badge
#

Nope, everything else in the bot is working perfectly fine so no overall issues but yeah it doesn't throw any error codes

#

Interesting....I added a print line to say when the cog is ready but its not sending that

#

So I don't think its reading the extension at all

fast osprey
#

I'd recommend putting in some logging

blissful badge
# fast osprey I'd recommend putting in some logging
import tomllib
import os
from dotenv import load_dotenv
from bot import Bot
from utils import Config
import logging

logging.basicConfig(level=logging.INFO)

class InvalidTokenException(Exception):
    pass

def main() -> None:
    DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
    if not DISCORD_TOKEN:
        raise InvalidTokenException("A Discord token was not set.")

    with open("config.toml", "rb") as config_file:
        config = Config(tomllib.load(config_file))

    bot = Bot(config)
    bot.run(DISCORD_TOKEN)

async def on_ready(self):
    print(f'{self.qualified_name} loaded')
    logging.info(f'Logged in as {self.bot.user.name} ({self.bot.user.id})')

if __name__ == "__main__":
    load_dotenv()
    main()```

would this do the trick?
#

I know I need some additional stuff on the commands themself of course

#

Oh interesting, I moved the button class before it defines the cog itself and its finally sending the print message I put in at the end of the extension.....that being said the listener event itself still isn't working

#

At least I know its reading the extension

fast osprey
#

What is Bot?

vapid parcel
#

How to separate Category in the on_guild_channel_update from Channels and Categories?

#

Because they seem to be together which is stupid GoofySkull

fast osprey
craggy anvil
#

How do i disable one button, only for the guy who clicked on it?

warm kettle
#

help lets say i have a command adv but it needs to be adv (item) but the user just types adv, it just gives me an error how can i change it so that if no (item) is given i send a message that you need and item, how would i do that?

jaunty cape
#

i'm not even going to attempt to write the code for you, it's just basic python

fast osprey
# jaunty cape if not args send message and return

This isn't how the library works. You don't get into the function at all if the user doesn't submit required arguments. The recommended approach is to make an error handler, either local to the command or global

jaunty cape
#

Wdym by “that’s not how it works”

quick gust
#

Why would u make it optional if ur end goal is to make it required? you see how incorrect that logically is? it's better to make an error handler and handle the error raised when arguments are missing.

jaunty cape
fast osprey
#

Error handlers don't have try excepts

quick gust
#

There doesn't need to be a try except block

#

An error handler typically uses if statements

fast osprey
#

Also the optionality of a parameter changes how it's displayed in help text. Making it optional to avoid needing to make an error handler would also mislead the user looking at the command's usage

quick gust
#

right

jaunty cape
#

just have smarter users

drowsy thunder
#

Can I add multiple databases in a single .db file?

merry cliff
#

I mean you can have multiple tables

#

if that's what you mean

jaunty cape
#

I mean you can have multiple tables

#

If that’s what you mean

#

I would show you if I had access to my DB browser rn

drowsy thunder
#

Can someone help me with this error

drowsy thunder
merry cliff
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.

drowsy thunder
#

Wait

#

Ping me when ur done

fast osprey
#

what are the python packages in this environment and their versions?

merry cliff
#

also Bot.session isn't a thing

drowsy thunder
#

So what can I do

merry cliff
#

just don't include the session arg when creating a webhook

jaunty cape
#

What the heck

fast osprey
#

That's not a thing that exists

jaunty cape
#

You mean Python 3.9.5?

drowsy thunder
#

I think python 3.9.5 ye

merry cliff
#

but not when you are using TextChannel.create_webhook

drowsy thunder
#

Dpy 2.3.2

fast osprey
#

It would also generally be helpful to have a traceback for any errors. Just the exception text isn't particularly useful

drowsy thunder
merry cliff
#

yep

jaunty cape
#

Irrelevant but I have the Linux kernel 6.11 btw

drowsy thunder
#

Me casually coding in a Android lmao

jaunty cape
#

Bruh just do that on your computer 😭

merry cliff
#

I can only imagine the suffering

drowsy thunder
jaunty cape
drowsy thunder
#

Nahh im fast typing in mobile

jaunty cape
#

I can’t imagine having to type brackets

drowsy thunder
#

An error occurred: session or client must be given @merry cliff

fast osprey
#

You can pass the bot into client=

drowsy thunder
drowsy thunder
fast osprey
#

the bot

drowsy thunder
#

What will I put after that

#

So client=bot

#

?

fast osprey
#

try it and see

drowsy thunder
#

@fast osprey also I have a file called botpfp.jpg so how can I read that and put it as webhook avatar?

jaunty cape
#

You can’t, you need a URL

#

(Maybe I’m thinking of Embeds)

drowsy thunder
fast osprey
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.

Changed in version 2\.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
drowsy thunder
#

image=read(botpfp.jpg)?

jaunty cape
drowsy thunder
drowsy thunder
fast osprey
#

Code and error?

fast osprey
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.
drowsy thunder
fast osprey
#

channel.create_webhook doesn't take a client

#

the docs above show this

drowsy thunder
#

So what do I do

fast osprey
#

Don't pass it in

drowsy thunder
#

If I don't it says it requires it

fast osprey
#

client= is a parameter to Webhook.from_url. You're calling entirely different methods here

merry cliff
#

webhook = await channel.create_webhook(name="BitBot Logging",client=bot) this is incorrect

#

you do not need it

#

just create it with the name

fast osprey
#

Webhook.from_url is a static class method, it needs to be told the client (bot) that's attached to it (or an aiohttp session).
channel.create_webhook is an instance method on an instance of a channel, which is already attached to your client (bot)

merry cliff
drowsy thunder
fast osprey
#

You did not

jaunty cape
#

Why do you keep explaining your code in your comments smh

#

Just say what the code does in a docstring

fast osprey
#

webhook = discord.Webhook.from_url(old_webhook_url)

drowsy thunder
fast osprey
#

Also "not working" isn't particularly helpful, and once again, you need to get yourself tracebacks if you are going to debug properly

#

otherwise you are just going to have to look over your entire code base trying to find where the problem is rather than your code telling you

jaunty cape
fast osprey
#

Looking over, this is just a matter of them doing a blanket try, except Exception and then throwing away the traceback

drowsy thunder
#

Also how to set the avatar as botpfp.jpg

#

Like how to read that

jaunty cape
#

You need a bytes object

exotic hazel
fast osprey
#

In this case, no. Blanket catches really should only exist in the highest level safety net error handling, which discord.py already has

blissful badge
fast osprey
#

Code?

drowsy thunder
# fast osprey Code?

Is dpy alligned with the new feature of bot emojis? If yes do you have docs for that?

fast osprey
#

What about them?

drowsy thunder
fast osprey
#

"Get" as in send them in a message?

drowsy thunder
fast osprey
#

You should be able to send them like you do any emoji afaik, library independent

#

<:emoji_name:id>

drowsy thunder
fast osprey
#

On that tab in the dev portal

drowsy thunder
lethal juniper
#

could anyone help?

drowsy thunder
#

Wait lemme see

#

Idk yk this doesn't show much detail

lethal juniper
#

what else should be there?

drowsy thunder
#

Ask @fast osprey

fast osprey
#

You can't use the @ui.select decorator for dynamic options

#

Well, at least you can't pass a dynamic list into the decorator itself. You could either make a Select subclass, or use the decorator and modify its options in the view's init

#

Either way, that list of options should be passed into the view, not accessed from a class attribute like you have

crude remnant
#

How do I make a bot start, I am new to using python

drowsy thunder
golden portal
#

heh

lethal juniper
fast osprey
#

You can't reference dynamic attributes in the decorator

lethal juniper
#

i mean available_items is always gonna change

lethal juniper
#

or you meant something else

fast osprey
#

You didn't

#

You set a property on the view named options

#

In the init, self.options is setting an attribute on the view itself. self.item_select is the Select itself

blissful badge
#
class WelcomeView(View):
    def __init__(self, member, recruitment_role_id, external_affairs_role_id, visitor_role_id, new_join_role_id):
        super().__init__(timeout=None)
        self.member = member
        self.recruitment_role_id = recruitment_role_id
        self.external_affairs_role_id = external_affairs_role_id
        self.visitor_role_id = visitor_role_id
        self.new_join_role_id = new_join_role_id

    @discord.ui.button(label="Open Recruitment Thread", style=discord.ButtonStyle.primary)
    async def open_recruitment_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer(ephemeral=True)
        recruitment_role = interaction.guild.get_role(self.recruitment_role_id)
        if recruitment_role:
            try:
                thread = await interaction.channel.create_thread(
                    name=f"Private thread with {recruitment_role.name}",
                    auto_archive_duration=60,
                    type=discord.ChannelType.private_thread
                )
                await thread.add_user(self.member)
                await thread.add_user(recruitment_role)
                await interaction.followup.send(f"Private thread created with {recruitment_role.name}", ephemeral=True)
            except discord.Forbidden:
                await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
        else:
            await interaction.followup.send("Failed to find the recruitment role.", ephemeral=True)

    @discord.ui.button(label="Open External Affairs Thread", style=discord.ButtonStyle.secondary)
    async def open_external_affairs_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer(ephemeral=True)
        external_affairs_role = interaction.guild.get_role(self.external_affairs_role_id)
        if external_affairs_role:
            try:
                thread = await interaction.channel.create_thread(
                    name=f"Private thread with {external_affairs_role.name}",
                    auto_archive_duration=60,
                    type=discord.ChannelType.private_thread
                )
                await thread.add_user(self.member)
                await thread.add_user(external_affairs_role)
                await interaction.followup.send(f"Private thread created with {external_affairs_role.name}", ephemeral=True)
            except discord.Forbidden:
                await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
        else:
            await interaction.followup.send("Failed to find the external affairs role.", ephemeral=True)

    @discord.ui.button(label="Assign Visitor Role", style=discord.ButtonStyle.success)
    async def assign_visitor_role(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer(ephemeral=True)
        visitor_role = interaction.guild.get_role(self.visitor_role_id)
        new_join_role = interaction.guild.get_role(self.new_join_role_id)
        if visitor_role and new_join_role:
            try:
                await self.member.add_roles(visitor_role)
                await self.member.remove_roles(new_join_role)
                await interaction.followup.send(f"Visitor role assigned and New Join role removed!", ephemeral=True)
            except discord.Forbidden:
                await interaction.followup.send("I do not have permission to manage roles.", ephemeral=True)
        else:
            await interaction.followup.send("Failed to find the specified roles.", ephemeral=True)```
#
class joinverification(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member):
        channel_id = 1230669525645660180  # Replace with your channel ID
        recruitment_role_id = 1198339491342065734  # Replace with your recruitment role ID
        external_affairs_role_id = 1230668342235234324  # Replace with your external affairs role ID
        visitor_role_id = 1081624269009715220  # Replace with your visitor role ID
        new_join_role_id = 1265108242221236289  # Replace with your new join role ID

        channel = self.bot.get_channel(channel_id)
        if channel:
            view = WelcomeView(member, recruitment_role_id, external_affairs_role_id, visitor_role_id, new_join_role_id)
            
            embed = discord.Embed(
                title="Welcome to the Server!",
                description=(
                    f"Hello {member.mention}, welcome to the server!\n\n"
                    "We're excited to have you here.\n\n"
                    "Feel free to explore and let us know if you have any questions.\n\n"
                    "Click the buttons below to get started!"
                ),
                color=discord.Color.blue()
            )
            embed.set_image(url="https://example.com/welcome-image.png")  # Replace with your image URL

            await channel.send(embed=embed, view=view)
        else:
            print(f"Failed to find the channel with ID {channel_id}")```
#
INTENTS = discord.Intents.default()
INTENTS.message_content = True
INTENTS.members = True
INTENTS.guilds = True```
#

intents ^

#

I tried adding some steps that would call out why it wasn't working if it encountered an issue but nothing really changed

fast osprey
#

How is INTENTS being used?

blissful badge
#

I am still learning so apologies for anything that is obvious that I am not getting

fast osprey
#

The code you sent just makes a variable named INTENTS

#

That doesn't do anything on its own

blissful badge
#

Oh oh oh

#

One moment

class Bot(commands.Bot):
    def __init__(self, config: Config, /) -> None:
        super().__init__(
            intents=INTENTS,
            command_prefix=commands.when_mentioned_or(config.prefix),
            allowed_mentions=discord.AllowedMentions(everyone=False),
            case_insensitive=True,
            activity=discord.Activity(
                type=discord.ActivityType.watching, name="Stanton"
            ),
        )
        self.config = config
        self.version = VERSION```
fast osprey
#

And it's your on_member_join that isn't working? I'd suggest putting some logging in there

blissful badge
fast osprey
#

What is the exact set of steps you are doing for that to happen, and what do you see?

blissful badge
fast osprey
#

Those buttons are different than the view class you just sent

blissful badge
#

I can send the code in its current form for the view

fast osprey
#

Send the code you are using currently please yes

blissful badge
#

Yup yup

#
class WelcomeView(View):
    def __init__(self, member, recruitment_role_id, external_affairs_role_id, visitor_role_id, new_join_role_id):
        super().__init__(timeout=None)
        self.member = member
        self.recruitment_role_id = recruitment_role_id
        self.external_affairs_role_id = external_affairs_role_id
        self.visitor_role_id = visitor_role_id
        self.new_join_role_id = new_join_role_id

    @discord.ui.button(label="Join Gjallarhorn", style=discord.ButtonStyle.primary)
    async def open_recruitment_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer(ephemeral=True)
        recruitment_role = interaction.guild.get_role(self.recruitment_role_id)
        if recruitment_role:
            try:
                thread = await interaction.channel.create_thread(
                    name=f"Private thread with {recruitment_role.name}",
                    auto_archive_duration=60,
                    type=discord.ChannelType.private_thread
                )
                await thread.add_user(self.member)
                await thread.add_user(recruitment_role)
                await interaction.followup.send(f"Private thread created with {recruitment_role.name}", ephemeral=True)
            except discord.Forbidden:
                await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
        else:
            await interaction.followup.send("Failed to find the recruitment role.", ephemeral=True)

    @discord.ui.button(label="Member of an Allied Org", style=discord.ButtonStyle.secondary)
    async def open_external_affairs_thread(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer(ephemeral=True)
        external_affairs_role = interaction.guild.get_role(self.external_affairs_role_id)
        if external_affairs_role:
            try:
                thread = await interaction.channel.create_thread(
                    name=f"Private thread with {external_affairs_role.name}",
                    auto_archive_duration=60,
                    type=discord.ChannelType.private_thread
                )
                await thread.add_user(self.member)
                await thread.add_user(external_affairs_role)
                await interaction.followup.send(f"Private thread created with {external_affairs_role.name}", ephemeral=True)
            except discord.Forbidden:
                await interaction.followup.send("I do not have permission to create threads.", ephemeral=True)
        else:
            await interaction.followup.send("Failed to find the external affairs role.", ephemeral=True)

    @discord.ui.button(label="Just Visiting", style=discord.ButtonStyle.success)
    async def assign_visitor_role(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.defer(ephemeral=True)
        visitor_role = interaction.guild.get_role(self.visitor_role_id)
        new_join_role = interaction.guild.get_role(self.new_join_role_id)
        if visitor_role and new_join_role:
            try:
                await self.member.add_roles(visitor_role)
                await self.member.remove_roles(new_join_role)
                await interaction.followup.send(f"Visitor role assigned and New Join role removed!", ephemeral=True)
            except discord.Forbidden:
                await interaction.followup.send("I do not have permission to manage roles.", ephemeral=True)
        else:
            await interaction.followup.send("Failed to find the specified roles.", ephemeral=True)```
fast osprey
#

Does that message pop up immediately after clicking the button, or after about 3 seconds?

blissful badge
#

Let me double check that, one moment

fast osprey
#

Also, could you paste everything you're getting in your terminal when you run the bot and do this?

blissful badge
# fast osprey Also, could you paste everything you're getting in your terminal when you run th...
Traceback (most recent call last):
  File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event
    await coro(*args, **kwargs)
  File "D:\Bots\Sigmund\extensions\joinleave.py", line 17, in on_member_join
    await channel.send(embed=embed)
  File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
    data = await state.http.send_message(channel.id, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 758, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Not a well formed URL.```
#

This is weird, I don't think this error is related to the buttons not working

#

Just an issue with the thumbnail, which is still working

#

but that being said, it says interaction failed I'd say more immediately than within 3 seconds

#

No errors being thrown in the terminal when buttons fail

#

will ad logging and see what it says

fast osprey
#

First thing to check is if you have an interaction url in the discord dev panel

blissful badge
#

Oh, good call, will do

blissful badge
amber moth
#

Why did this happen out of sudden

fast osprey
fast osprey
# amber moth

You're hosting your bot in a place you shouldn't be

amber moth
#

How

#

It works normally but it just happened rn

fast osprey
#

Because you are hosting your bot in a place you shouldn't be

amber moth
#

no im using pylexnodes it can host bots

fast osprey
#

Clearly it cannot

amber moth
#

I made many bots in that website

#

but this error happened rn out of sudden

fast osprey
#

Because something happened to work in the past does not mean it was the right decision, or that it will continue working

#

"Free" hosts are universally scams. It is not a sustainable business model

amber moth
#

It's saying I got rate limited

#

did you see the 2nd picture

fast osprey
#

I did

amber moth
#

I think it's because i made the sync commands thing inside on_ready

#

I forgot to remove it

fast osprey
#

That would not result in that error, but you also should not be putting basically anything in on_ready

amber moth
#

Okay

blissful badge
#

Doing this broke the other member join stuff so will sort through that and try removing that link and see what it does

fast osprey
#

Setting that URL means that discord will post interactions to the URL you specify, rather than being sent as a gateway event (which is how discord.py and other libraries function)

blissful badge
#

miserable, i appreciate all your help though

fast osprey
#

Not really sure what you mean by "invites to my alt"

#

But if you can't really mix and match http interactions with gateway interactions (discord.py etc)

#

They get sent to one or the other

blissful badge
blissful badge
# fast osprey They get sent to one or the other

Super weird, this seemed to have introduced a new error that wasn't happening before. This is just for the basic member join notification to our welcome channel. Seems to be from the thumbnail.

  File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event
    await coro(*args, **kwargs)
  File "D:\Bots\Sigmund\extensions\joinleave.py", line 17, in on_member_join
    await channel.send(embed=embed)
  File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 1618, in send
    data = await state.http.send_message(channel.id, params=params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\VirtualBoxes\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 758, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Not a well formed URL.```
#

Unrelated but, still annoying

#

@fast osprey removing that HTTP looks like it fixed it, its giving me some permissions error which I thought I had accounted for (easy fix) but no more interaction failed!!!

#

the above error is still an issue, but one I think I can fix

fast osprey
lethal juniper
#

how do I make those button persistent?

#

wanted to add bot.add_view(ItemSelectMenu) and bot.add_view(ItemButtonMenu) to the on.ready event, but realized I need to pass available_itemsto ItemSelectMenu, and available_items is a list which values are defined in ItemButtonMenu. Is there any simple way to fix this? Or do i need to define available_items outside of ItemButtonMenu?

fast osprey
#

You shouldn't be using on_ready for things you want to happen reliably or once

lethal juniper
#

I want to make buttons work even after reloading bot

fast osprey
#

on_ready is not the place for that

#

or pretty much anything 99% of people use it for

lethal juniper
#

so where should I add add_view then?

fast osprey
#

That said, if your bot originally relied on sending multiple view instances each with their own state, then you can't get away with just persisting a single view instance when the bot wakes up

fast osprey
fast osprey
# fast osprey That said, if your bot originally relied on sending multiple view instances each...

Your options here are:

  1. Remove the need for state, and have a singular view instance with no parameters handle all interactions on all messages matching that view
  2. Remember the state for each instance of the view (message) you're sending, then call add_view that many times passing in the message id so you can recreate that state
  3. Shift entirely away from persisting views to use dynamic items
jaunty cape
amber moth
mild token
#

how i can know via bot when someone boost the server?

fast osprey
#

There is not a definitive way, all you can do is guess

mild token
#

if someone role gets updated?

fast osprey
#

That wouldn't tell you if someone who already had the role boosted again

mild token
fast osprey
#

People can boost multiple times

mild token
#

only discord assigns it

mild token
fast osprey
#

That methodology would not tell you if someone boosted a second time. They already have the role

#

Same with premium_since

mild token
fast osprey
#

Huh

#

That's not the case I'm describing

#

Someone boosted earlier. They have the role and premium_since. They boost again. Your code doesn't see anything

#

The closest thing you can do is listen for the system message, but that also has false negatives

mild token
fast osprey
#

Discord simply does not communicate this directly to bots

#

All you can do is guess

dry kelp
#

How can we check in disnake library if a user is already timed out?

wanton current
#

!d discord.Member.timed_out_until

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None if the user is not timed out.

New in version 2.0.

craggy anvil
#

i have firstview.py

and it has this function:

    async def reset_embed(self, interaction):
        if interaction.message.embeds and len(interaction.message.embeds) > 0:
            embed = interaction.message.embeds[0]
            if len(embed.fields) >= 2:
                embed.set_field_at(0, name=f"Sending {self.currency}", value="`None`", inline=True)
                embed.set_field_at(1, name=f"Receiving {self.currency}", value="`None`", inline=True)
            else:
                print("Not enough fields in the embed to reset.")

            self.children[0].disabled = False
            self.children[1].disabled = False

            await interaction.message.edit(embed=embed)
        else:
            print("No embed found to reset.")

And that's for a reset button in specific embed, but there's like one more embed for confirmation after this(it's in another file, in class), that has incorrect and correct button, i want to pass reset_embed function to that incorrect button to do, so it resets the original embed and it deletes the interaction.message with that incorrect button, i hope soemone understood 😭

cunning frost
#

who can help for a discord bot in dms

#

i can give the code, i just can't make the discord bot

#

so i kinda need help or someone make it for me

brazen crane
#

i'm not too proud about my ability on discord bots but i can try to help u

#

dont dm please

#

o wait

#

im gotta be afk somethingirl

cunning frost
#

ok thanks

mild token
glad marsh
#

Are you supposed to have several database files? Or should I have one with several tables?

quick gust
#

You probably don't need multiple databases

primal pilot
#

How can interaction.response.send_message raise discord.errors.InteractionResponded: This interaction has already been responded to before, when interaction.is_expired returns False?

#

I've been debugging this for hours 😅

quick gust
#

are u deferring it?

torn solar
#

if your deferring it you need to do interaction.followup.send

primal pilot
#

I'm not deferring it. Even deferring it raises the same issue

torn solar
#

send the code then please

primal pilot
#

Give me a moment and I'll send a code snippet. It's for the Code Jam, so I'll make a small example from it rather than sharing the exact code

primal pilot
# torn solar send the code then please
class QuestionView:
    def __init__(self) -> None:
        super().__init__()
        self.next_interaction: Interaction | None = None

    @discord.ui.button(
        label="Incorrect answer",
        style=discord.ButtonStyle.danger,
    )
    async def incorrect_answer(self, interaction: discord.Interaction, _: discord.ui.Button) -> None:
        self.next_interaction = interaction
        self.stop()

And this is the class that is using QuestionView: ```py
class Level(Protocol):
async def return_to_view(self, interaction):
...
await interaction.response.send_message(file=img, embed=embed, view=view)

async def run():
    next_interaction = interaction
    for question in self.questions:
        question_view = question.view()  # A QuestionView instance
        await next_interaction.response.edit_message(
            embed=question.embed(),
            view=question_view,
            attachments=[],
        )
        await question_view.wait()
        next_interaction = question_view.next_interaction
    await self.return_to_view(interaction)
#

There's more code in reality, but it should be unrelated. Basically what's happening is that when the discord UI button is pressed, the interaction is stored in QuestionView.next_interaction and the QuestionView is stopped. The Level class waits for QuestionView to be stopped and then gets the question_view.next_interaction in order to let the next question continue from that interaction

#

When all questions are looped through, self.return_to_view(interaction) uses the last interaction to return to a different view. However, this interaction fails for some reason. And I don't think it's been responded to, especially since interaction.is_expired is false if called right before the interaction.response.send_message

#

Seems like interaction.edit_original_response instead of interaction.response.send_message works, but Discord says Interaction failed in response to the button press? Wtf

fast osprey
#

You generally should not be storing interactions imo. They are very stateful and short lived, ideally they should be handled in the direct handler and then discarded

primal pilot
#

For a TextInput in a modal, is there a way to make the user's input have python code highlighting?

#

I'm able to change the style to paragraph, so it's accepting long input strings, but can't find a good way to get syntax highlighting to work

fast osprey
#

Not supported afaik

primal pilot
#

Do you know if there's a way to have a description in a modal, or any text field that the user can't edit? Can't find anything like that either

manic sage
#

Does anybody here knows some good hosting for python bot that is on server with 8k members? I need it to have servers in EU, so it has low latency

fast osprey
fast osprey
manic sage
craggy anvil
fast osprey
hushed galleon
lethal juniper
#

how to make different amount of decorators every time function is called?

fast osprey
#

What's the functional thing you're trying to accomplish?

lethal juniper
#

I've got list: available_items: [['1', '2', '3', ..... '25'], ['26', '27', ..... '50], ...] and every time it's got different amount of items (between 1 and 4). I've also got a button, pressing which calls 4 SelectMenus. Every SelectMenu has its own options depending on items in available_items. The thing is, if available_items got less than 4 lists, it'll raise an error list index is out of range (because available_items[4] doesn't exist anymore).

#

I suck at explaining lemme provide code

fast osprey
#

Not sure what the decorators have to do with what you're asking

#

This feels just like logic you need to implement when you're setting those options

lethal juniper
#

or can i somehow disable it

#

?

fast osprey
#

You can disable the select yes

lethal juniper
#
@client.command()
async def item(ctx):
    view = ItemButtonMenu()
    await ctx.send("Choose an option:", view=view)

class ItemButtonMenu(ui.View):
    def __init__ (self, *, timeout=None):
        self.available_items = []
        self.available_items_for_user = []
        super().__init__(timeout=timeout)
    
    @ui.button(label = 'Take item', custom_id = 'take_item', style = discord.ButtonStyle.green)
    async def take_item(self, interaction: discord.Interaction, button: ui.Button):
        with open('items.csv', 'r') as csvfile:
            csvreader = csv.reader(csvfile)
            next(csvreader)
            self.available_items = [row[0] for row in csvreader if row[1] == '']
        view = ItemSelectMenu(self.available_items)
        await interaction.response.send_message(view=view, ephemeral=True)

class ItemSelectMenu(ui.View):
    def __init__(self, available_items, timeout=None):
        super().__init__(timeout=timeout)
        def chunks(lst, n):
            for i in range (0, len(lst), n):
                yield lst[i:i+n]
        self.children[0].disabled = True
        self.children[1].disabled = True
        self.children[2].disabled = True
        self.children[3].disabled = True
        for i in range(len(list(chunks(available_items, 25)))):
            self.children[i].max_values = len(list(chunks(available_items, 25))[i])
            self.children[i].options = [discord.SelectOption(label=item) for item in list(chunks(available_items, 25))[i]]
            self.children[i].disabled = False
    @ui.select(placeholder='Choose an item')
    async def select_callback_0...
    @ui.select(placeholder='Choose an item')
    async def select_callback_1...
    @ui.select(placeholder='Choose an item')
    async def select_callback_2...
    @ui.select(placeholder='Choose an item')
    async def select_callback_3...
#
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ui\view.py", line 430, in _scheduled_task
    await item.callback(interaction)
  File "F:\Projects\discord-bot/main.py", line 135, in take_item
    await interaction.response.send_message(view=view, ephemeral=True)
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\interactions.py", line 855, in send_message
    await adapter.create_interaction_response(
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\webhook\async_.py", line 223, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.3.components.0.options: This field is required
#

Why does it happen

fast osprey
#

You are sending over a select with no options

lethal juniper
#

can options be empty?

fast osprey
#

Nope

lethal juniper
#

oh ye i've got how to do this

#

ty

craggy anvil
#
    @discord.ui.button(label="View Transaction", style=discord.ButtonStyle.link)
    async def view_transaction(self, interaction: discord.Interaction, button):
        button.url = f'https://etherscan.io/tx/{self.tx_hash}'

Is this right code for redirect button for embed discordbot

finite salmon
craggy anvil
#

ty anyways

finite salmon
#

alr

glad marsh
sick birch
sick birch
#

well that is unfortunate

wispy falcon
#

help im new to cogs and somehow its not working

fast osprey
#

What about it isn't working?

wispy falcon
#

i mean

#

When I type Bot Test in a channel, the bot doesn't send "Bot is working"

fast osprey
#

Have you done any debugging to see what is happening?

#

If you're getting into that method at all?

fast osprey
#

add_cog is async, you need to await it

jaunty cape
fast osprey
#

setup is only required in extensions