#discord-bots

1 messages · Page 239 of 1

reef gazelle
#

same

#

we’ll probably not actually i’m 2000

rustic panther
#

i have to take python in my degree of study for my bachelors

cold sonnet
#

yeah my way of picking a random number was kinda shit

#

I'm realizing after seeing that message

vocal snow
cold sonnet
#

I haven't done this in 2 years either

reef gazelle
#

hahahah born in 2000 my bad

rustic panther
#

nope born in the 70's

reef gazelle
cold sonnet
rustic panther
#

where can i post a snippet of a program ?

reef gazelle
#

sheeesh

vocal snow
unkempt canyonBOT
#
Pasting large amounts of code

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

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

cold sonnet
#

discordpy is basically the same as twitchio

#

it was so relieving to see

#

are there any other platforms python has a similar module for

rustic panther
#

alright here is my attempt at that question i asked

slate swan
#

you coulda just pasted that here

#
import random

def generate_six_random_numbers():
    numbers = []
    counter = 0
    while len(numbers) < 6:
        random_number = random.randint(1, 69)
        if random_number not in numbers:
            numbers.append(random_number)
        counter += 1
    return numbers
vocal snow
unkempt canyonBOT
#

@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.

[34131, 28189, 62461, 63624, 92476]
vocal snow
#

a shorter version

naive briar
#

Hi 🐈

rustic panther
#

@vocal snow i like that. so everything i had was all wrong then

vocal snow
rustic panther
#

ok cool thank you

#

for whatever reason it didnt work for me

#

im using python 3.11 on a windows machine

vocal snow
# rustic panther for whatever reason it didnt work for me

!e ```py
import random

def generate_six_random_numbers():
numbers = []
counter = 0
while len(numbers) < 6:
random_number = random.randint(1, 69)
if random_number not in numbers:
numbers.append(random_number)
counter += 1
return numbers

print(generate_six_random_numbers())

unkempt canyonBOT
#

@vocal snow :white_check_mark: Your 3.11 eval job has completed with return code 0.

[35, 19, 56, 8, 38, 49]
rustic panther
#

yeah mine doesnt output anything

#

do i need to actually use linux then ?

vocal snow
#

no

vocal snow
rustic panther
#

then i am doing something wrong, i thought i was

rustic panther
#

how do i call the function

slate swan
#

my_function**()**

#

the () means you are calling my_function

rustic panther
#

which is what i was thinking with the def generate_random_numbers()

plucky sun
#

@vocal snowhow to make private interaction response

vocal snow
#

ephemeral kwarg

#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

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

Responds to this interaction by sending a message.
unkempt mauve
#

why isnt one of my command is not syncing when syncing it manually with a command as well as auto syncing. but my others are synced like give warn, search warn, remove warn, check warn but transfer warn is not syncing

white citrus
#

How can i play adios with a discord bot

unkempt mauve
#

why tho?

#

you can do something like:

user = <userid here>

if user.guild.id == <guild id here>:
    print('yes')
else:
    print('no')```
#

its not js code btw

#

yes u can have a loop

#

for that

#

and this server is not related to javascript in any way

#

this server is not for javascript

#

go to some javascript servers

slate swan
#
guild_id = 0
member_ids = [
  123,
  321
]

guild = client.get_guild(guild_id)

for member in guild.members:
  if member.id in member_ids:
    print(member)
white citrus
#

How can i play audios with a discord bot

flint stirrup
#

@reef gazelle are your looking for Red bot?

reef gazelle
#

no clue ahaha

#

Trying to load cogs so I can separate commands into files

flint stirrup
#

Well cogs are a thing for Red bot, not the Python bot

reef gazelle
#

Im just tryina find out how to use em

slate swan
#

cogs aren't working for me for some reason

#

i had to write the whole thing in my main file

glad cradle
slate swan
#

I cleared the whole thing

#

A website?

#

You can't run discord.js on a website

#

You need to use node.js

glad cradle
#

zeffo ducky_sphere

slate swan
vocal snow
#

this is the python server, please ask discord.js questions in their server: discord.gg/djs

slate swan
#

This isn't really about creating discord bots but the python bot in this server is giving me blank messages. Anybody knows how to fix this?

vocal snow
#

what do you mean its giving you blank messages?

slate swan
#

can I send a screenshot here?

vocal snow
#

yes

slate swan
hushed galleon
slate swan
#

I haven't changed any discord settings

#

do i have to enable it?

hushed galleon
#

should look something like this

slate swan
#

ok lemme check

sweet ledge
#

Hi

slate swan
#

bruh

#

it's a programming language

#

learn it

slate swan
flint stirrup
#

(if it existed)

reef gazelle
#

Thanks

white citrus
#

How can i play audios with a discord bot

reef gazelle
#

Cog wont load cant figure out why?

#

Got it loading

#

command just not working now

vocal snow
#

you've done _int_

#

and the command is indented inside it, it should be in the class

reef gazelle
#

Thank you 🤦‍♂️

#

Cant access bot.latency from inside ping

#

using self.bot.latency but still

#

Dont think the bot is being passed in so treating self as the Ping class

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 490, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\Maja-Beta\bot.py", line 241, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 890, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\Maja-Beta\modules\voice\cog.py", line 45, in voice_join
    audio_source = nextcord.FFmpegPCMAudio("audios\\moderator_call.mp3")
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\player.py", line 281, in __init__
    super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\player.py", line 144, in __init__
    self._process: subprocess.Popen = self._spawn_process(args, **kwargs)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\player.py", line 163, in _spawn_process
    raise ClientException(executable + " was not found.") from None
nextcord.errors.ClientException: ffmpeg was not found.```
reef gazelle
#

Calling an mp3 when its expecting a ffmpeg maybe?

reef gazelle
vocal snow
white citrus
vocal snow
#

which VPS are you using?

#

if its a standard linux machine you can install it from whichever package manager

white citrus
vocal snow
#

i have no clue what that is

reef gazelle
#

No errors and the cog loads fine but the embed is not sending do I need to intent embeds or something?

white citrus
plucky sun
#

@vocal snow```
Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\KokoG\PycharmProjects\Logger\main.py", line 163, in clear
await interaction.response.send_message("Done",limit=amount,ephemeral=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'limit'

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

Traceback (most recent call last):
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\KokoG\PycharmProjects\Logger\venv\Lib\site-packages\discord\app_commands\commands.py", line 856, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'limit'

white citrus
#

Can i play local audios without ffmpeg in a discord bot?

azure quiver
#

I’ve been having trouble registering my slash commands for my but using the py-cord library. What is the code I need to add to have my slash commands show up in the discord prompt when typing /

shrewd apex
shrewd apex
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
shrewd apex
#

await interaction.channel.purge(limit=amount)

shrewd apex
#

!d discord.ext.commands.Bot.tree

unkempt canyonBOT
#

property tree```
The command tree responsible for handling the application commands in this bot.

New in version 2.0.
shrewd apex
#

then use sync method belonging to the tree

#

so
await bot.tree.sync()

shrewd apex
reef gazelle
shrewd apex
#

show ur file structure

reef gazelle
#

Cogs

shrewd apex
#

send a screen shot

reef gazelle
#

will do just in kitchen right now

white citrus
reef gazelle
#

It was working fine but i adjusted it to be a embed instead

#

and it broke since

shrewd apex
white citrus
shrewd apex
# white citrus fly.io

i mean as long as u include ffmpeg.exe in same directory as root it should work right?

shrewd apex
white citrus
shrewd apex
reef gazelle
#

or where it’s called in on ready

shrewd apex
#

under

white citrus
shrewd apex
unkempt canyonBOT
#

class discord.VoiceClient```
Represents a Discord voice connection.

You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").

Warning

In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus "discord.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio")) or the library will not be able to transmit audio.
white citrus
#

There is no inter.voice_client.play

slate swan
unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
white citrus
slate swan
#

voice_client is property so you dont call it

manic steeple
#

Hello, I need help please with making a bar graph. Here is my code below and I am trying to set the x-axis as all the states and then the y-axis as the number of shipments. I'm not sure what to inser in the plt.bar() so it outputs just the names of the states and the values corresponding to them. I've been at this for hours ._. I am very beginner.

slate swan
slim delta
#

Hey, I copy pasted some code that I found on overflow, but something is wrong, I tried to modify the code but I can't figure out what to change. Can someone help me please?

shrewd apex
reef gazelle
#

@shrewd apex

#

Not loading it is it

slim delta
#

I have another question tho, do I have to invite the bot to each discord?

shrewd apex
reef gazelle
shrewd apex
shrewd apex
reef gazelle
#

odd, thanks

#

Should I change the way its loading, you said to use a setup hook?

slim delta
shrewd apex
slim delta
white citrus
#

Why is he playing 2 time audio_search_a

                await inter.response.defer(ephemeral=True)
                vc = await inter.user.voice.channel.connect()
                await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
                check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
                re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
                await inter.edit_original_message(embed=re_connected, file=check_mark_png)
                audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
                vc.play(audio_source_a)
                while vc.is_playing():
                    await asyncio.sleep(5)
                
                audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
                vc.play(audio_source_b)```
knotty mountain
#

can a message have multiple embeds?

reef gazelle
#

@shrewd apex Still no luck can you assist?

#

Should I use bot.start instead and put in a main function

shrewd apex
#

show ur file structure

#

send a ss

reef gazelle
shrewd apex
#

hmm

reef gazelle
#

Some online say to use bot.start instead and a main function with asyncio.run to start the bot

#

Im not loading the load_cogs() at all right now

#

cause not sure where to be putting it

shrewd apex
#
import asyncio

bot.setup_hook = load_cogs

async def load_cogs():
  print("Loading cogs...")
  for file in os.listdir('cogs'):
    if file.endswith('.py') and not file.startswith('_'):
      await bot.load_extension(f"cogs.{file[:-3]}")
      print(f"Loaded {file}")
  print("Loaded all cogs")

bot.run("token")
#

try this

reef gazelle
#

Where does setup hook go

#

in onready or

shrewd apex
#

nowhere

#

its called internally

reef gazelle
reef gazelle
#

ah yeh thanks

#

didn't spot that think it auto added

#

load_cogs is not defined

#

Done

#

Cause I put it above the function

shrewd apex
#

mb yeah

reef gazelle
#

Still doesnt look to be loading

#

Its finding it but not actually loading it in :/

#

wait

#

used the wrong prefix forgot I changed it to a ! been trying $ for a while ahah

shrewd apex
#

💀

reef gazelle
shrewd apex
#

add f

#

in the f string

reef gazelle
#

yep

smoky sinew
reef gazelle
#

blindly writing shit

#

true programmer

shrewd apex
#

happens i effed up for like 1 hour yesterday where i constucted some nested matrix and committed a memory issue which gave wrong updates i spent like an hour+ to discover

#

copy.deepcopy to the save

reef gazelle
#

I should prob take a step back into the basics for few days then go back to discord.py hahah

#

If I just put something random after prefix it tries to treat as a command and is throwing error but I had a check for CommandNotFound

#

If I just do like !1

shrewd apex
#

add a check in the error handler

reef gazelle
#

Ah yeh typeError

#

or not

smoky sinew
slate swan
unkempt canyonBOT
#

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

The default command error handler provided by the bot.

By default this logs to the library logger, however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for command error.

Changed in version 2.0: `context` and `exception` parameters are now positional-only. Instead of writing to `sys.stderr` this now uses the library logger.
slate swan
#

It takes context and exception

#

And you only accept exception in your code

reef gazelle
#

Yh was just needing ctx

#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, CommandNotFound):
        return
    raise error
slate swan
#

python joeCollapse

reef gazelle
#

my bad yoo

slate swan
#

You can just say py btw

reef gazelle
#

thanks

slate swan
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

reef gazelle
#

😉

reef gazelle
#

Yeah it is now

#

I didnt have ctx before but it was working earlier or maybe I deleted some how

slate swan
#

When it's sending 2 arguments it must accept both

#

So it could not work without ctx param

reef gazelle
#

If I want to create additional folders under cogs directory so like ping is cogs/utility and I can have some in like cogs/fun

Do I have to modify the for loop or can I use like cogs/* for subdirectorys

slate swan
#

You have to modify the for loop adding the extensions to go this one directory deeper

reef gazelle
#

Little roll dice command

merry cliff
#

nice

reef gazelle
#

If I am handling an error how can I stop it from still outputting to console am I doing something wrong?

smoky sinew
reef gazelle
#

Inside the cog

smoky sinew
#

why do you have a cog and extension for each command

#

but it's because if needs to be replaced with elif

reef gazelle
reef gazelle
smoky sinew
#

show your code now

reef gazelle
#
    @coinflip.error
    async def value_error(self, ctx, error):
        if isinstance(error, MissingRequiredArgument):
            await ctx.send(f"{ctx.message.author.mention} Choose heads or tails!", delete_after=6.0)
        elif isinstance(error, CommandInvokeError):
            return
        else:
            raise error
smoky sinew
#

weird

reef gazelle
#

Dunno if do to with that "ignoring"

#

Due to a on_command_error in main file

#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, CommandNotFound):
        return
    else:
        raise error
#

I have this so cant just spam commands that don't exist if I remove it then the other handlers work and dont output to console but then you can spam console

reef gazelle
#

any1?

flint stirrup
#

Can you post a bigger section of the code

reef gazelle
#

Error & Code

smoky sinew
#

where's the elif..

reef gazelle
#

So right now its handling commands that dont exist correctly but if I do like !cf without a choice then it errors but its still sending the error so dunno why its showing in console

#

I put the elif in and it didnt change

smoky sinew
#

this is what it's doing now

#

the missingrequiredargument and the commandinvokeerror are two separate if statements

#

so it's just doing ctx.send and then raise error

reef gazelle
#

thought u can nest ifs and which ever it hits first will run

#

oh i see

smoky sinew
#

yes but it's not stopping after that

flint stirrup
#

Well you're not nesting them anyways

reef gazelle
#

Can I just return under the await or is elif better then

smoky sinew
#

elif is probably better

flint stirrup
#

elif is better

reef gazelle
#

Other errors are gone just this in console now

smoky sinew
#

are you doing print(error) anywhere by chance

reef gazelle
#

Ah yeh i pasted something else in before to try grab some more info

#

Need to modify this

#

What Im using so cant just do ! then anything like !1 !2

smoky sinew
#

just do ```py
if not isinstance(error, CommandNotFoundError):
raise error

reef gazelle
#

forgot ctx put it back

smoky sinew
#

commands.CommandNotFound

reef gazelle
#

Working but now the coinflip spits error

#

if u just do !cf even tho it gets handled

#

but just fixed it before :/

flint stirrup
#

I'm trying to understand what you're doing here: what commands are you running that cause the error? What is the correct way to run those commands so hey don't cause an error?

reef gazelle
#

Im just running !cf so it sends a message "Choose heads or tails" so its argument is heads or tails

#

It gets handled but spits the error into console still

flint stirrup
#

Well I can see you're trying to send an embed, but it doesn't actually get sent. So you can try writing a try-except around the different commands in the coinflip function to see what is causing the error

reef gazelle
#

recent screenshot

naive briar
#

What's the problem

reef gazelle
#

Just trying to handle errors for coinflip like not putting heads or tails.. or if the user inputs a number instead or if they put nothing at all

#

Given up goin to bed try again in few days aha

stoic tree
#

So buddy... let me explain this, so ip pingers are not consider as you may say "Illegealgwseh"

stoic tree
stoic tree
#

do i user {user.mention} in dsicord.py to ping somone

misty bobcat
#

How do I invite my bot to a server? (Help me idgaf if you're saying bruh behind the screen)

#

I think I got it hold on...

sick birch
boreal pebble
#

how should i make a bot message in my account in time intervals

misty bobcat
#

im confused at this part can somebody help me?

#

?

#

What do i add on here in order for it to work?


import discord

# Create a new client or bot instance
client = discord.Client()  # or discord.Bot()

# Set the token
client.token = token

# Your bot's code goes here

@bot.event
async def on_ready():
    print(f'{bot.user} has connected to Discord!')
@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    if message.content.startswith('!Ask'):
        await message.channel.send('Hello!')


# Run the bot
client.run(client.token)```
#

nvm

round blade
#

Can I use pyttx3 with dc.py

misty bobcat
vocal snow
#

you need to enable message content intent

rugged shadow
#

that code is very GPT-y

unkempt mauve
vocal snow
#

no, can you show your code?

unkempt mauve
vocal snow
#

yes

unkempt mauve
#

large code since two commands are inside the group

vocal snow
#

is the entire group not syncing or a particular command?

unkempt mauve
#

4 other groups has the same name for the subcommand

vocal snow
#

you don't have a warn subcommand for this group

unkempt mauve
vocal snow
#

got it, just making sure

unkempt mauve
#

I am basically talking about search and random subcommand

#

4 other groups has it too

vocal snow
#

are you sure the cog is loaded properly?

unkempt mauve
#

yes, I saw in the pycache

#

I reloaded it manually with a command too

vocal snow
#

and you synced the tree after?

unkempt mauve
#

I synced it auto and manually as well

#

it first reloaded

#

then I synced

slate swan
#

Anyone who can help?

#

thanks

dry kelp
#

So back to what i fixed can be problematic, because if i remove the guild icon the config.icon will be None

#

and because the value will be None i can't check it like if config.icon and if config.icon is not None

#

Because basically it's a database value, and inside there is not like empty there still is a value which is None so that will break thru the check

#

As you can see i made a quick test to see if it's possible to check

white citrus
#

Why is he playing 2 time audio_search_a

                await inter.response.defer(ephemeral=True)
                vc = await inter.user.voice.channel.connect()
                await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
                check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
                re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
                await inter.edit_original_message(embed=re_connected, file=check_mark_png)
                audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
                vc.play(audio_source_a)
                while vc.is_playing():
                    await asyncio.sleep(5)
                
                audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
                vc.play(audio_source_b)```
vale wing
vocal snow
#
                while vc.is_playing():
                    await asyncio.sleep(5)
``` what is this for
#

oh is it to sleep till the song is finished

#

just use the after parameter of .play

vale wing
#

Generally to switch to next track you do that yeah

dry kelp
vocal snow
dry kelp
#

So basically

slate swan
#

example for discord Modal

dry kelp
#

When a server setups a welcomer using my bot if the icon gets removed after setup will destroy the build_embed config

#

But what i want to make is to send the welcomer just without the icon/banner

#

The reason the value is empty is because in database at first the value is null

#

So there is like a empty value that fucks up the check

#

Here i was trying to check

#

But in fact there's no icon URL

#

And i can't even check if the content startswith http or something because that would fail directly, it is empty

#

already tried

#

I also tried checking if guild icon is not true

vocal snow
#

is the icon supposed to be the guild icon?

dry kelp
#

Yep

vocal snow
#

does it really need to be in the database at all?

#

you could just store the guild id and access all data of the guild

dry kelp
#

How else do u wanna setup a welcomer?

#

I have to store the values

vocal snow
#

no, you don't

dry kelp
#

How can you remember the color of embed?

vocal snow
#

if the icon is supposed to be the guild icon there's no reason to store it

dry kelp
#

How can you remember text on the embed?

vocal snow
#

I am not talking about those at all

dry kelp
#

Well yeah you are right about icon

vocal snow
#

just storing the guild id would allow you to get the guild via bot.get_guild, then access it's data

dry kelp
#

You are right but other images?

vocal snow
#

then it's a simple check to see if guild.icon is None or not

dry kelp
#

guild icon is just an example

#

But there can be set any images

#

as long URL is available

#

But in that case there already is a handler if it won't show up

#

My problem rn is if before guild icon was set

#

then removed, stops the entire embed build

#

So the real question is

#

How can i check if the value is empty?

dry kelp
#

Nvm im dumb, fixed

thin raft
# dry kelp

Why don't you use the embed class directly?

jovial patrol
jovial patrol
# unkempt mauve whats the error?

its supposed to create a discord channel with the name of the survant and the survants choices whenever someone gives in the survey

#

but it does not

unkempt mauve
jovial patrol
unkempt mauve
#

install discord lmao

#

pip install discord

jovial patrol
#

wait see im hosting the bot code on a website

#

no erros and i took it to vscode and the terminal gave me some annoying stuff

unkempt mauve
#

maybe in line 79,
it should be channel = await guild.create_text_channel(name=channel_name, category=category)

#

you probably forgot the name param

jovial patrol
unkempt mauve
#

try adding a name= before channel_name in line 79

jovial patrol
unkempt mauve
jovial patrol
# unkempt mauve try this

channel = await guild.create_text_channel(name=channel_name, category=category) paste this in line 79?

unkempt mauve
#

yes

jovial patrol
unkempt mauve
#

without error, I cant solve either :v

#

does your bot has proper permission?

jovial patrol
# jovial patrol still not working

i also added the print here 1 thing right? see the code and when i do the %create_channel thing there is no "here 1" in the output console maybe that helps

jovial patrol
#

this the output

unkempt mauve
#

u need to try this on vsc, they might give u the error

#

its really strange

jovial patrol
slate swan
#

Can someone help me on this code

jovial patrol
unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan
#

it didnt say hi

slate swan
#

it didnt say/send hello to me

#

can someone fix it?

unkempt mauve
slate swan
jovial patrol
unkempt mauve
slate swan
unkempt mauve
#

ad an if statement

#

and match the ids

#

just do if statement

#

in the code

#

where u add the commands in the embed

#

no, matching the ids

#

if the author id isnt same as the dev id, it will not show the dev command

jovial patrol
jovial patrol
#

aight so i want it to be like a ticket system

unkempt mauve
#

how can the code not work without giving an error

#

thats weird for me ngl

jovial patrol
#

firstly tho, does the code make hypothetically snese?

#

that it posts the resulst

jovial patrol
#

does it even make sense?

unkempt mauve
#
import gspread
from oauth2client.service_account import ServiceAccountCredentials```
What are even these
naive briar
unkempt mauve
#

wait yes I didnt noticed he has two of them

naive briar
#

At the line 81

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return  # Ignore command not found errors

You're overriding the previous handler and ignoring all exceptions

#

(you're not re-raising them)

unkempt mauve
#

oo, thats why I think why he has no errors

jovial patrol
#

yea so what should i do

unkempt mauve
#

cuz u already have the correct one defined above

jovial patrol
#

@unkempt mauve @naive briar just delete this?

naive briar
#

Delete the whole second handler

jovial patrol
#

i used to code but now im mroe into video editin,...

unkempt mauve
jovial patrol
unkempt mauve
#

backspace

naive briar
#

Delete the whole error handler at the line 81 to the line 84

jovial patrol
#

did

#

you said raise too?

unkempt mauve
#

now retry and give us error

jovial patrol
#

no error

naive briar
#

What's the code now

jovial patrol
#

to be clear i deleted this

jovial patrol
unkempt mauve
jovial patrol
unkempt mauve
#

perfect

naive briar
idle lantern
#

when making a variable like money which holds money how do i store that?

#

open a json file ?

naive briar
#

A database

lean harbor
#

import discord
from discord.ext import commands

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

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

item_info = {
'item1': 'This is information about item1.',
'item2': 'This is information about item2.',
'item3': 'This is information about item3.',
}

@bot.command()
async def info(ctx, item: str):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')

This doesn't work for some reason when i do !info item1

naive briar
#

(JSON isn't a database)

lean harbor
#

anyone know why?

idle lantern
#

do i need to learn sqlite now? x.x

jovial patrol
naive briar
#

IDK what it is 🤷

#

Just know that it's probably empty

jovial patrol
#

@naive briar if i want to host my bot on replit, do i need to post the code + json file and stuff on github first?

naive briar
#

No

jovial patrol
# naive briar No

so it just has acces to the json file even tho its on my local pc?

idle lantern
jovial patrol
#

oh shit im an idiot @naive briar @unkempt mauve
there is a lot of errors

naive briar
slate swan
lean harbor
unkempt mauve
#

it was peace before the line 81's handler got removed

jovial patrol
naive briar
unkempt mauve
#

ur reaction lol

jovial patrol
lean harbor
# slate swan Enable message_content intent

import discord
from discord.ext import commands

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

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

item_info = {
'item1': 'This is information about item1.',
'item2': 'This is information about item2.',
'item3': 'This is information about item3.',
}

@bot.command()
async def info(ctx, item: str):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')

Like this?

slate swan
#

Don't ask me just try

naive briar
#

Hi me just try

slate swan
lean harbor
jovial patrol
#

wait omg its actually errors @naive briar @unkempt mauve those happen when i do the %create_channel command

naive briar
unkempt mauve
#

and ask us if u r facing problems

idle lantern
jovial patrol
idle lantern
#

if i said something stupid pls dont kill me

unkempt mauve
jovial patrol
naive briar
unkempt mauve
slate swan
idle lantern
lean harbor
#

ye thanks

idle lantern
#

thanks

naive briar
idle lantern
#

oh

idle lantern
slate swan
#

can someone give me a code that sends an embed when i say the word?

lean harbor
#

Btw is there any way to put what the bot says anything that the bot says in a simple box

#

like this

slate swan
#

how

#

lol this dude

jovial patrol
#

@naive briar @unkempt mauve fixing the code 1by1 encountered a stopping point, what does that mean?

slate swan
#

Just put the value to send in backticks

lean harbor
#

ah right thanks!

lean harbor
slate swan
#

how to make me discord bot if i say hi it will say hello.???

slate swan
tall temple
#

pls can someone help me ?

#
Traceback (most recent call last):
  File "/home/debian/t.o./main.py", line 367, in <module>
    discord = Discord()
  File "/home/debian/t.o./main.py", line 30, in __init__
    self.songs = json.loads(f.read())
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 5970 column 9 (char 196579)
vocal snow
#

Unterminated string starting at: line 5970 column 9

#

check that line

tall temple
vocal snow
#

well the error is coming from the json file so why are you checking the script

lean harbor
slate swan
lean harbor
#

the and how to make it look like the screenshot i gave you above

tall temple
#

that's the 5970th line ...

slate swan
unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

I don't have anything more than that

#

And I'm on phone currently

lean harbor
jovial patrol
lean harbor
slate swan
#

Never connected to excel using python so no idea

#

You need to look on the internet for that

tall temple
#

pls can someone help me ?

#
Traceback (most recent call last):
  File "/home/debian/t.o./main.py", line 367, in <module>
    discord = Discord()
  File "/home/debian/t.o./main.py", line 30, in __init__
    self.songs = json.loads(f.read())
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 5970 column 9 (char 196579)
slate swan
#

Show lines above and below it

tall temple
slate swan
#

Try using json.load instead

#

!d json.load

unkempt canyonBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).

*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).

*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
slate swan
#

And pass f instead of f.read()

tall temple
glad cradle
#

if you're using the json module with a discord Bot - depending how you're running its functions - that's not a good idea

jovial patrol
slate swan
slate swan
tall temple
jovial patrol
slate swan
tall temple
#

instead of json.loads

glad cradle
#

you're receiving a 404 Not Found response from the google API

jovial patrol
slate swan
slate swan
jovial patrol
tall temple
#

but it's working on my windows machine

slate swan
#

It takes file object not it's contents

tall temple
#

and i receive this error only in my linux vps ...

slate swan
#

So f instead of f.read

tall temple
glad cradle
slate swan
slate swan
#

Not in a discord bots channel ^-^

jovial patrol
#

aksed on forums aswell

glad cradle
slate swan
tall temple
# slate swan So f instead of f.read
Traceback (most recent call last):
  File "/home/debian/t.o./main.py", line 367, in <module>
    discord = Discord()
  File "/home/debian/t.o./main.py", line 30, in __init__
    self.songs = json.load(f)
  File "/usr/lib/python3.9/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Unterminated string starting at: line 5970 column 9 (char 196579)
jovial patrol
# slate swan

good point, but doesnt the thread get deleted after a while?

slate swan
jovial patrol
slate swan
#

I suggest you include actual error in title and tags and not discord bots

#

So somebody who worked with Google api can help and not somebody who knows discord bots

jovial patrol
slate swan
#

Close and make a new one

jovial patrol
lean harbor
#

seems. So complicated.

#

!pastebin

unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan
jovial patrol
lean harbor
#

https://paste.pythondiscord.com/duhebodidu - This is my code, the item info seem to be taking up ALOT of space in my main.py is there any way i can move this code to another folder just for storing the data? And also would it be possible to categorise the items?

jovial patrol
slate swan
#

!rule 10

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

lean harbor
# slate swan !rule10

yes but does it really affect people around me? it's not like i'm trying to help people with chat gpt

slate swan
#

@fierce crag

lean harbor
#

you can ping the mods all you want or use @novel apex

slate swan
lean harbor
#

i doubt they would care especially when i'm just trying to figure out how to do something

lean harbor
slate swan
#

unless I ask asking to code for me about if i say hi and he will respond hello it doesnt even work (dont react quickly i have installed discord)

lean harbor
slate swan
jovial patrol
#

its fine tho cuz cooldown over

slate swan
#

you are supposed to run !close

jovial patrol
#

oh lmaoo

slate swan
#

in it

jovial patrol
#

my bad

gilded oxide
#
     @commands.command()
     async def help(self, ctx):
        select = Select(options=[
            discord.SelectOption(label="Moderation", emoji="![Settings](https://cdn.discordapp.com/emojis/1106974031007207434.webp?size=128 "Settings")", description="")])
        view = View()
        view.add_item(select)
        await ctx.send("**Help Below**", view=view)``` the menu won't send it will only send the jsk extension help command?? and ik i have description empty bc im not done
slate swan
lean harbor
#

you make no sense

north kiln
slate swan
#

!rule 10 only applies when someone uses ai tools to help others

unkempt canyonBOT
#

10. Do not copy and paste answers from ChatGPT or similar AI tools.

slate swan
#

on your own you can do whatever you want so pinging mods is pointless there

lean harbor
jovial patrol
slate swan
lean harbor
#

??

slate swan
# slate swan its also bannable

like i said it is when the person uses it to provide help in the python discord but using it on your own has nothing to do with this server

#

he just copy and paste it/ or taking photo

#

period

lean harbor
#

doubt you would know anything

north kiln
lean harbor
#

mmm

slate swan
#

this is #discord-bots so if you have something to talk about move to dms or elsewhere @lean harbor@slate swan

lean harbor
#

how would you import this item info into the main.py?

fierce monolith
#

Hello everyone. For my first python project I wanted to create a discord bot. But I keep running into errors that I don't know how to fix. Can someone make me a direct message so I can explain the issue? I don't want to spam the python help forum or this chat with my newbie problems

north kiln
#

Making a help post is completely fine

north kiln
fierce monolith
#

I was trying to make a roll bot for a TTRPG to roll different random things. I thought it would be a smart idea to split the main.py with cogs to cog_rolltables.py and then my database randomrolls.yaml.

Now no matter what I do, when I try to run it on replit.com it keeps giving me an error or nothing at all happens and the console just says "cog_rolltables.py" but nothing more

slate swan
lean harbor
#

ah nvm

north kiln
#

So you put your command in another file

lean harbor
#

i did it the other way around thanks!

north kiln
#

Did you load it?

#

Or could you describe how you structure your code

fierce monolith
#

`import discord
import os
import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=',', intents=intents)

token = os.environ['TOKEN']

Load Cogs

@bot.event
async def on_ready():
await load_cogs()

async def load_cogs():
for filename in os.listdir('./Cogs'):
if filename.endswith('.py') and filename != 'init.py':
await bot.load_extension(f'Cogs.{filename[:-3]}')
print(filename)

@bot.command()
async def load(ctx, extension):
await bot.load_extension(f'cog_rolltables.{extension}')
await ctx.send(f'loaded {extension}')

@bot.command()
async def reload(ctx, extension):
await bot.load_extension(f'cog_rolltables.{extension}')
await ctx.send(f'reloaded {extension}')

@bot.command()
async def unload(ctx, extension):
await bot.load_extension(f'cog_rolltables.{extension}')
await ctx.send(f'unloaded {extension}')

Run the bot

async def main():
async with bot:
await bot.load_extension('cog_rolltables')
await bot.start(token)

Run the bot

async def main():
await bot.start(token)
print("Bot has started successfully!")

Run the main function

if name == "main":
asyncio.run(main())`

#

And my cog_rolltables code:
`import discord
from discord.ext import commands
import random
import yaml

class Rolltables(commands.Cog):
def init(self, bot):
self.bot = bot

# 1 BUILDING TYPES  
@commands.command()
async def Building(self, ctx):
    # Load the YAML file containing roll tables
    with open("RandomRolls.yaml", "r") as file:
        roll_tables = yaml.safe_load(file)

    # Check if the roll tables exist
    if roll_tables:
        # Roll on each table
        table1_result = random.choice(list(roll_tables["1_Building_Type"].values()))
        table2_result = random.choice(list(roll_tables["1_Building_Feature"].values()))
        table3_result = random.choice(list(roll_tables["1_Quirky_Style"].values()))
        table4_result = random.choice(list(roll_tables["1_Quirky_State"].values()))
        table5_result = random.choice(list(roll_tables["1_Quirky_Feature"].values()))
        table6_result = random.choice(list(roll_tables["1_Quirky_Secret"].values()))
      
        # Construct the final message
        message = f"You see a {table1_result} that is {table2_result} with a {table3_result} style and {table4_result} look. There are {table5_result} and a secret {table6_result}."

        # Send the message as a response
        await ctx.send(message)
    else:
        await ctx.send("Table not found.")

async def setup(bot):
await bot.add_cog(Rolltables(bot))`

north kiln
#

Uhh why do you have 2 main()

fierce monolith
#

oh ... that slipped me because I copied the code back from a debugger

north kiln
#

Did you try reloading the extension with your message command first?

fierce monolith
#

I can't even get the bot to connect to my discord. replit is throwing error messages at me and stops the script

cloud dawn
#

!code

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

fierce monolith
#
Traceback (most recent call last):
  File "main.py", line 47, in <module>
    asyncio.run(main())
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "main.py", line 42, in main
    await bot.load_extension('cog_rolltables')
  File "/home/runner/SRTTRPGDISCORDBOT/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1011, in load_extension
    raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'cog_rolltables' could not be loaded.
 
KeyboardInterrupt
 
cloud dawn
#

It's an import so you cannot just make up a name.

north kiln
cloud dawn
#

Then it should be Cogs.rolltables

north kiln
#

Use Cogs.rolltables

fierce monolith
#

I'd love to be able to use cogs, so I can create different functionality in a plug-and-play style. But I am too much of a newbie to deal with cogs it seems. I am sorry if I ask stupid questions that might be obvious for you guys.

The cog_rolltables.py is in a folder called Cogs on Replit

cloud dawn
#

There are no stupid questions.

north kiln
#

Not cog_rolltables or anything

fierce monolith
#

I renamed cog_rolltables.py to Cogs.rolltables.py and adapted the code but still get error messages:

import os
import asyncio
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=',', intents=intents)

token = os.environ['TOKEN']

# Load Cogs
@bot.event
async def on_ready():
    await load_cogs()

async def load_cogs():
    for filename in os.listdir('./Cogs'):
        if filename.endswith('.py') and filename != '__init__.py':
            await bot.load_extension(f'Cogs.{filename[:-3]}')
            print(filename)


@bot.command()
async def load(ctx, extension):
    await bot.load_extension(f'Cogs.rolltables.{extension}')
    await ctx.send(f'loaded {extension}')

@bot.command()
async def reload(ctx, extension):
    await bot.load_extension(f'Cogs.rolltables.{extension}')
    await ctx.send(f'reloaded {extension}')

@bot.command()
async def unload(ctx, extension):
    await bot.load_extension(f'Cogs.rolltables.{extension}')
    await ctx.send(f'unloaded {extension}')

# Run the bot
async def main():
    async with bot:
        await bot.load_extension('Cogs.rolltables')
        await bot.start(token)

# Run the main function
if __name__ == "__main__":
    asyncio.run(main())```
north kiln
#

Nonono

fierce monolith
#

With the error message:
Traceback (most recent call last):
File "main.py", line 47, in <module>
asyncio.run(main())
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/hd4cc9rh83j291r5539hkf6qd8lgiikb-python3-3.10.8/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "main.py", line 42, in main
await bot.load_extension('Cogs.rolltables')
File "/home/runner/SRTTRPGDISCORDBOT/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1011, in load_extension
raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'Cogs.rolltables' could not be loaded.

north kiln
#

Not how you name the file

#

But the loading extension code

cloud dawn
#

Just name the file rolltables

north kiln
cloud dawn
#

But idk why you are hard coding it if you already have a function that takes all the cogs.

fierce monolith
#

I've been trying so many solutions until I didn't understand it properly anymore. I read on stackoverflow the code of someone who made it work and tried to copy and ended up with this

north kiln
#

The official docs on extensions should be clear enough

cloud dawn
#

Is outdated tough.

north kiln
#

Well in what means

#

I don't really know

cloud dawn
#

Well other than the add command not awaited not much

fierce monolith
#

I'll think I will just start from scratch and work my way to a working code piece by piece and delete all the things I saw on Stackoverflow. I can't get it to work. Thanks everyone anyway for all suggestions

lean harbor
#

' ': '__** [ ~ Info Command ~ ]**__ \n`Description: Allows you to search up information and trade value of a specific item. \nNote: You need to type the exact name of the item with no capital letter. If it is 2 words or more use a underscore(_) instead of a space. \nUsage: !info [item name] \nExample: !info pumpkin_fedora `',

#

why does this not work? I did !info and it did nothing

cloud dawn
# fierce monolith I renamed cog_rolltables.py to Cogs.rolltables.py and adapted the code but still...
import os
import logging
import asyncio

import discord

from discord import Intents
from discord.ext.commands import Bot
from discord.ext import commands

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")


class AwesomeBot(Bot):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    async def load_cogs() -> None:
        for filename in os.listdir('./Cogs'):
            if filename.endswith('.py') and filename != '__init__.py':
                await bot.load_extension(f'Cogs.{filename[:-3]}')
                logger.info(filename)

    @staticmethod
    def on_ready() -> None:
        logger.info("I'm online!")

    def setup_hook(self) -> None:
        await self.load_cogs()


async def main() -> None:
    intents = discord.Intents.default()
    intents.members = True

    bot = AwesomeBot(command_prefix=',', intents=intents)

    async with bot:
        await bot.start(os.environ['TOKEN'])

# Run the main function
if __name__ == "__main__":
    asyncio.run(main())
cloud dawn
lean harbor
lean harbor
# cloud dawn Could you show the whole command?

import discord
from discord.ext import commands
from item_info import item_info

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

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

@bot.command()
async def info(ctx, item: str):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')

#

thats it and in item info i just have similar codes to what i sent above which works.

lean harbor
cloud dawn
#

Do other commands work?

lean harbor
lean harbor
#

an error

cloud dawn
#

That means you didn't provide an item in the command.

lean harbor
#

theres no item to provide.

cloud dawn
#

But there is..?

#

async def info(ctx, item: str):

#

item right there.

lean harbor
# cloud dawn But there is..?

oh you meant, but that doesn't make any sense. since the line of code that i gave you is in a py file called item_info

cloud dawn
#

I mean you have it there in the function but you still ask for an item. What do you want/ expect to happen?

lean harbor
#

it's supposed to be used like this:
!info [item name]

cloud dawn
#

Oh okay, well why not use the error handler that discord.py has build in?

#

Otherwise you would need to do that for every new command.

lean harbor
#

But the problem now is figuring out why this code doesn't work btw @cloud dawn you know a way to infinitely keep a bot online which website do you recommend

cloud dawn
cloud dawn
cloud dawn
# lean harbor aight thx

You'd need to do this ```py
@bot.command()
async def info(ctx, item: str = None):
if item in item_info:
await ctx.send(item_info[item])
else:
await ctx.send(f'Sorry, I do not have information about {item}.')

#

Now it's an optional argument.

lean harbor
#

Sorry, I do not have information about None.

#

thats what it says

cloud dawn
#

Then it works right?

#

That's what you made right now, you can expand it but like I said it's very manual. Exmaple:

#
@bot.command()
async def info(ctx, item: str = None):
    if not item:
        await ctx.send("Please provide an item or put general info here or smth")
    elif item in item_info:
        await ctx.send(item_info[item])
    else:
        await ctx.send(f'Sorry, I do not have information about {item}.')
smoky sinew
cloud dawn
#

And return None and be indicated as not to call function and use the name kwarg instead of the function name and use the discord command handler

#

yes

smoky sinew
#

no

#

discord.py gets the command name from the function name automatically

cloud dawn
#

But you shouldn't use it.

smoky sinew
#

why not

cloud dawn
#
@bot.command(name="info")
async def _info(ctx, item: str | None = None) -> None:
    if not item:
        await ctx.send("Please provide an item or put general info here or smth")
    elif item in item_info:
        await ctx.send(item_info[item])
    else:
        await ctx.send(f'Sorry, I do not have information about {item}.')
smoky sinew
#

no

#

that's not what you should do at all

cloud dawn
#

Well it's a function you should not call standalone so yes I'd use this in production.

cloud dawn
hushed galleon
#

if naming the function the same as what you want the command to be invoked as is impossible (i.e. using illegal characters), or would cause a namespace collision with other variables you've defined, then the name= kwarg would be necessary, otherwise its merely preference

cloud dawn
#

Indeed but if I'd be working on it with multiple people I'd enforce the underscore.

hushed galleon
#

then thats your style convention, i.e. preference

cloud dawn
#

Omw pr on black

smoky sinew
#

that's different from just correcting the type hint

cloud dawn
#

It's either a string or None

smoky sinew
#

you didn't type hint ctx either, and black does not enforce naming conventions

hushed galleon
#

who says they cant? ducky_devil

glad cradle
#

what a battle

vocal snow
glad cradle
#

lmao

cloud dawn
#

I can't really say who "won" but if it's a tie we're teenagers.

smoky sinew
#

💀

cloud dawn
slate swan
vivid axle
#

im trying to make a simple game using buttons on dpy and i cant figure how to make thing i wanna wait_for a button press but idk how???

cloud dawn
#

wait_for? Buttons have a timeout.

vivid axle
#

i dont know how

#

i have never used buttons

#

sorry

cloud dawn
#

Here is an example.

vivid axle
#

ok

cloud dawn
#

@vivid axle What is important here is that you just need to make the View then use it in the command.

vivid axle
#

where should i make the class for confirm because i need to use a class that is already created inside the commadn

cloud dawn
#

You can put it outside the cog class

vivid axle
#

i need to use a class that make inside the command tho?

cloud dawn
#

I don't exactly know what you mean.

lean harbor
vivid axle
#

i have a class i made

#

and i make a instance of it in the command which i need to run a function on with the game

cloud dawn
vivid axle
#

lol

cloud dawn
vivid axle
#

i managed to get it to work, but im edititng the message i send with the view, but how can i stop it from saying interaction failed when i press the button?

cloud dawn
vivid axle
#

confused

cloud dawn
vivid axle
#

oh

smoky sinew
#

just do view=None

vivid axle
#

im so confuse

smoky sinew
#

show your code

vivid axle
#

hold

lean harbor
vivid axle
#

!

#

@unkempt canyon

#

how to paste bin python

smoky sinew
vivid axle
#

i think i broke it hold on

smoky sinew
#

why are you defining the view inside the command

vivid axle
#

i need to put a finction insode it that is for a object i make inside class

#

like

smoky sinew
#

what does that mean

vivid axle
#
class e:
  def cool(self):
    return 'hi'

def hello():
  a = e()
  class fortnite:
    def hi(self):
      print(a.cool())
  fortnite.hi()```
#

like that but fortnite is the view

#

this is so confusing

#

i wish it was less complicate 😭

smoky sinew
#

you don't need an inner class at all

#

you're not using a at all in your btns class

vivid axle
#

i give up

swift acorn
#

Hey could anyone please tell me how I can make an input option, optional in a slash command

swift acorn
slate swan
swift acorn
slate swan
#

you set it in the function signature

swift acorn
#

Oh so I just make this

async def sendmessage(interaction: discord.Interaction, message_to_send: str, reply_id: str):

This

async def sendmessage(interaction: discord.Interaction, message_to_send: str, reply_id: None):
#

yeah that's an error nvm lol

slate swan
#

no

#

: str is a typehint

#

you need to add default value

#

so something: str = None

#

and to be fully correct with typehints you should do this: something: str | None = None

gilded oxide
#

what are some util commands I should add to my bot

patent wagon
#

my discord bot it not working for one person in perticular

#

like not even his alt can preform any functions

#

how do i fix this

#

(ping pls)

potent spear
patent wagon
#

it just doesnt work for him

potent spear
patent wagon
#

thats all that the problem is

#

i tried copying same perms as the other bot that worked

#

and noting happend

#

it works for everyone else

#

like every other account

#

can preform functions ok

#

other then this person

potent spear
#

so he's typing commands in your guild and the bot doesn't respond to it?

potent spear
#

do you have an on_message event in your bot which proves it can actually read when the user sends a message?

patent wagon
#

i believe so

#

let me check again

potent spear
#

you also haven't provided any code yet, which is basically me guessing the issue

patent wagon
#

any code doesnt work

#

for this one singular dude

potent spear
patent wagon
#

no matter roles nor server

potent spear
#

are you sure he's actually a friend and not just trolling?

patent wagon
potent spear
# patent wagon no matter the code

show me your on_message and a proof your bot can't read whenever this person sends a message in a channel (but DOES when you or someone else does)

slate swan
#

howcome

#

its meant to work

#

nvm found a fix

open gorge
#

hey where i can find good source to learn py boot in discord?

austere prairie
# open gorge hey where i can find good source to learn py boot in discord?

https://realpython.com/how-to-make-a-discord-bot-python/ this guide is pretty good, just make sure to specify bot intents because it's a bit outdated

In this step-by-step tutorial, you'll learn how to make a Discord bot in Python and interact with several APIs. You'll learn how to handle events, accept commands, validate and verify input, and all the basics that can help you create useful and exciting automations!

lean harbor
#

How to use embed for discord bot messages?

vocal snow
lean harbor
#

Will it work if I just .embed the name of the variable

vocal snow
#

what

lean harbor
#

Lemme show you

#

!pastebin

unkempt canyonBOT
#
Pasting large amounts of code

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

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

lean harbor
vocal snow
#

that question makes no sense

#

will what work?

lean harbor
vocal snow
#

what do you mean "just embed the item_info"

lean harbor
#

all the stuff in the variable item_info

vocal snow
#

!d discord.Embed

unkempt canyonBOT
#

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

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

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

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
vocal snow
#
embed = Embed(title="Item Info", description="Some text")
await ctx.send(embed=embed)
#

you can add fields with embed.add_field

#

you can check the other methods in the doc

lean harbor
#

thanks

lean harbor
north kiln
#

for what I see you should use a field

#

perhaps multiple embeds as there could be more than 25 items

lean harbor
#

i've got loads of items which each line is basically 1 command (E.g !info [item])

#

and i've got about 30 different items which all need an embed

#

how would i do that?

north kiln
#

so sth like
!item pumpkin_fedora ?

#

and show an embed of it?

lean harbor
#

and yes i want to embed the info, with maybe a picture and maybe a link in the title which links to the wiki

north kiln
#

I have been doing that lol

lean harbor
#

lol how did you do it

north kiln
lean harbor
north kiln
#

Embed(title=param, description=item_info.get(param))

#

sth like that I suppose

lean harbor
north kiln
#

no

lean harbor
#

do i need to import it?

north kiln
#

obviously

#

aren't you using dpy already

#

??

knotty mountain
#

How can I remove some administrative commands from the help section?

lean harbor
north kiln
#

Embed is actually discord.Embed if you mean by that

vocal snow
lean harbor
#

await ctx.send(embed=embed) where would i put this?

#

in this code?

north kiln
#

line 18

lean harbor
north kiln
#

isn't that what you want

lean harbor
north kiln
#

what's the error then

lean harbor
north kiln
#

uh

lean harbor
#

i don't think this will actually work as intended. Because the user is supposed to do !info (item)

north kiln
#

you didn't pass the item input

#

you passed the whole dict

lean harbor
#

but how will the bot know which item you are supposed to do

north kiln
#

that's in the command parameter

lean harbor
north kiln
#

you build the embed based of it

#

?

#

idk what you want then

#

do you want to show all items or only a single item

lean harbor
#

not the whole dicitionary

north kiln
#

yes then put line that defined the embed inside the command function

#

and use item instead of item_info

lean harbor
#

as i said lol i'm very new.

north kiln
#

move that line into the if statement

lean harbor
north kiln
#
if item in item_info:
    embed = Embed(title=item, description=item_info.get(item))
    await ctx.send(embed=embed)
lean harbor
#

lemme see if this works

north kiln
#

?

#

you sent another message

#

did you read your code

lean harbor
north kiln
#

you have another ctx.send() before the embed was sent

lean harbor
#

i'm confused what you mean.

north kiln
#

umm

#

I don't think there's any problem with this

#

maybe reload your bot

lean harbor
#

aight

lean harbor
# north kiln umm

OH WAIT i know why it's because im using replit for my bot to be online 24/7

#

i need to update that code lol

#

works thanks!

formal basin
#

Hello I’m making a verify command and I keep getting this error and I don’t understand

slate swan
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

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

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

slate swan