#discord-bots

1 messages · Page 301 of 1

humble lily
#

@desert kiln while trying to use ur code I met this problem

Traceback (most recent call last):
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 803, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 745, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

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

Traceback (most recent call last):
  File "C:\Users\blomo\Desktop\Unive Kriminell Bot\ny.py", line 16, in <module>
    bot.run('YOUR_BOT_TOKEN')
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 612, in login
    data = await self.http.static_login(token)
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 807, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000015A06F06C20>
Traceback (most recent call last):
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
    self._check_closed()
  File "C:\Users\blomo\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed```
desert kiln
humble lily
#

It is

desert kiln
#

or you didn't put one on bot.run('')

humble lily
mortal flower
desert kiln
#

is it in-between the 2 ''?

mortal flower
#

as you can see :)

humble lily
final iron
#

His issue is an import issue, not a token issue

desert kiln
desert kiln
final iron
#

Why does this even matter

#

You have an import issue, not a token issue

humble lily
#

I don't know how to solve it please help me

final iron
#

Solve what

humble lily
final iron
#

Already been explained

#

Bot isn't an attribute of discord

#

You need to use discord.ext.commands.Bot

humble lily
#

While trying to use discord.ext.commands.Bot it just gives me another error?

final iron
#

And better yet, swap to discord.py instead of disnake/pycord

#

Which is...

humble lily
#

How do i swap

#

@final iron

mighty pilot
final iron
#
import os
import sys

py_exec = sys.executable
uninstall_list = " -m pip uninstall nextcord py-cord interactions.py disnake dislash discord-py-slash-command discord.py-message-components enhanced-discord.py novus hata discord-interactions discord.py-self discord.py-self.embed discord2 python-discord reactionmenu discord_py_buttons discord_slash discord.py discord discord-ext-forms discord-ext-alternatives dpy-appcommands discord-ext-slash"

os.system(py_exec + uninstall_list)
os.system(py_exec + " -m pip install discord.py --no-cache-dir")
mighty pilot
#

Welcome to troubleshooting

final iron
#

Run this in a file

final iron
#

I think it's outdated anyway

humble lily
#
C:\Users\blomo\AppData\Local\Programs\Python\Python310\python.exe: No module named pip```
final iron
#

Are you using a venv

humble lily
#

What is a venv

final iron
#

You'll probably have to add pip to path as well tbh

unkempt canyonBOT
#
Virtual environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
humble lily
#

Damn this is hard

mighty pilot
#

It's easier if you know python first

final iron
#

What IDE are you using

humble lily
#

I don't know, how do I check?

final iron
#

i stg

humble lily
final iron
#

When you're writing code, what app are you using

humble lily
#

And this is where I got my eyes open for

final iron
#

Some video guide probably exists then

final iron
mighty pilot
humble lily
#

I have tried checking for days now

final iron
#

...

#

First result

#

That'll probably be easier to follow

humble lily
#

Problem is that I don't know what to google

final iron
#

I gave you a webpage...

#

That, and the tag will let you setup a venv

#

After that, if the error is still being produced you might've not added pip to path

#

Then, once we fix that you'll run the bit of code I gave you

dry sedge
#

incase discord adds bots to gcs how can you make a bot join a voice call or how would you make it join a voice call

unkempt canyonBOT
#

class discord.VoiceChannel```
Represents a Discord guild voice channel.

x == y Checks if two channels are equal.

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

hash(x) Returns the channel’s hash.

str(x) Returns the channel’s name.
dire mason
#

would this change when i add an icon to the bot?

final iron
#

Yes

#

Should

unkempt canyonBOT
#
Missing required argument

package

dire mason
#

How do I get the author to a slash command?

quick brook
#

interaction.user

final iron
unkempt canyonBOT
dire mason
# quick brook interaction.user
 @app_commands.command(name="mention")
    async def slash_mention(self, interaction):
        await interaction.response.send_message(interaction.user.mention, ephemeral=True)```

So this?
dire mason
# quick brook yes

question, for some reason its not showing up as a command in the slash menu, any reason for that?

quick brook
quick brook
#

App commands work differently from message commands, they're handled mostly on Discord's end. Discord just tells your bot when someone successfully triggers a command.
In order to do this, you need to register your commands on the command tree then tell discord they exist by syncing with tree.sync.
Commands can be registered on the tree either as a global command or as a guild-specific command, and must be synced to the same scope they are associated with in the tree.
When you sync, you are telling Discord about the commands you currently have for a particular scope.

To sync global commands: await tree.sync()
To sync guild commands: await tree.sync(guild=guild)
Guilds must be either a Guild object or a discord.Object with the guild's id.

It may help to think of the tree as a dict like this.

{
  None: [global, commands],
  guild_one: [guild, one, commands],
  guild_two: [guild, two, commands]
}

copy_global_to will copy [global, commands] and add them to the commands for the guild you pass.
This is only done locally, you must still sync.

All commands are global by default. There are a few ways to make them guild-specific:

  • @app_commands.guilds() decorator on an app_commands.Group sublcass or @app_commands.command()
  • guild/guilds in @tree.command()
  • guild/guilds in bot.add_cog, only if the cog is a GroupCog
  • guild/guilds in tree.add_command, not typically used

A common practice for syncing is to pick a specific guild for testing and run tree.copy_global_to(guild=guild) then tree.sync(guild=guild).
When you're done testing, tree.clear_commands(guild=guild) then tree.sync(guild=guild).
When you're ready to publish your commands, tree.sync().

This command makes the process pretty straightforward and easy to work with. I would recommend reading the bottom section on how it works

dire mason
#

I got it.

#

I already made it.

#

Btw, really improving I think

quick brook
#

that's nice to hear

dire mason
quick brook
dire mason
quick brook
final iron
#

Any idea on why this wouldn't be returning the data

  connection = await asqlite.connect("RatioData.db")
  cursor: asqlite.Cursor = await connection.cursor()
  await cursor.execute(f"SELECT * FROM {country}")
  print(country)
  ratio_info = await cursor.fetchone()
  print(ratio_info)
dire mason
final iron
#

Usually it would return a tuple with the data

#

I can access the data like this

print(ratio_info[(ratio_info.keys())[0]])
#

But it's pretty messy, and I dunno why it's not returning a tuple like last time

dusk dagger
hushed galleon
final iron
twilit grotto
#

why not just use on_ready event

#

for the cog

final iron
#

Because you shouldn't be using on_ready for really, anything except for printing that your bot is online

hushed galleon
final iron
hushed galleon
#

nothing obvious in the source code to suggest it wouldnt set the row_factory correctly

final iron
#

It actually does return a Row

#

I could've sworn it was a tuple

#

I was using aiosqlite before, then I transitioned to asqlite

#

I guess they have different functionality

hushed galleon
#

iirc aiosqlite doesnt auto-set the row factory

final iron
#

It was just a drag and drop change when I swapped so I thought they functioned basicaly the exact same

#

Yeah I unpacked it, seems like it's working now

#

Thanks

quick brook
#

duh it's slash commands

#

idk if you can even read the first line of code

#

then why ask?

#

custom prefixes are much more harder and he is just learning. so no

#

i mean i would be interested to see how you handle custom prefixes

#

lol

#

idk where you store your custom prefixes

quick gust
#

in a microsoft word file

quick brook
quick gust
#

oh u prefer excel?

quick brook
#

excel is jackshit for dbots

#

why write to a file when you can just use a database instead

quick gust
#

I was joking bro 💀

quick brook
#

no tonetags so taking it seriously

quick gust
#

tonetags?

quick brook
#

you'll be suprised by the amount of people actually using like a file as a database

quick gust
#

oh the /j shit

quick brook
#

i have seen people using google sheets to store dbot data

quick gust
#

they really depricate someone's ability to understand sarcasm, I hate em sometimes

quick brook
#

it's happened before

quick gust
quick brook
#

but it's not

quick gust
#

that's insane

buoyant quail
#

database.docx ⚔️

onyx elk
#

oi anyone know tf this means?

slate swan
#

you probably have some code blocking your event loop

glad cradle
#

oof 2950 seconds

onyx elk
#

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

slate swan
#

You likely have more code that you don't share

onyx elk
onyx elk
# slate swan You likely have more code that you don't share

allowed_user_id = '992087776747061259'

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

@client.tree.command()
async def hello(interaction: discord.Interaction):
    """Says hello!"""
    await interaction.response.send_message(f'Hi, {interaction.user.mention}')

@client.tree.command()
async def invite(interaction: discord.Interaction):
    """Sends the bot's invite link with permission."""
    bot_client_id = '1139339241650921502'
    
    bot_permissions = discord.Permissions(administrator=True)
    
    invite_link = discord.utils.oauth_url(bot_client_id, permissions=bot_permissions)```
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.

slate swan
#

And that's still not the entire code

onyx elk
quick brook
#

Why are you serving a flask app with your bot?

rugged shadow
#

inb4 replit + uptimerobot

rough shuttle
#

how to sync global commands

naive briar
#

Sync without specifying the guild argument

rough shuttle
#

oh okay

#

thx it worked

slate swan
#
class UsersSelect(discord.ui.View):
    def __init__(self, bot):
        super().__init__()

        self.bot = bot
        self.timeout = None

        self.select = discord.ui.user_select(
            custom_id="UsersSelect",
            placeholder="Нажмите, чтобы выбрать участников (до 5)"
        )

        self.add_item(self.select)```
```py
case "changeaccess":
    await interaction.response.send_message("Выберите участника в меню ниже", ephemeral=True, view=UsersSelect(self.bot))

raise TypeError(f"expected Item not {item.__class__!r}") TypeError: expected Item not <class 'function'> - error
What am I doing wrong?

quick gust
#

what are you trying to achieve? a select menu?

slate swan
quick gust
buoyant quail
#

Huh
That's interesting
I knew only about standart select

shrewd fjord
slate swan
buoyant quail
#

It's created the same

#

I just tried it

slate swan
buoyant quail
#

What error?

slate swan
#

raise TypeError(f"expected Item not {item.__class__!r}") TypeError: expected Item not <class 'function'>

#

full traceback

slate swan
# slate swan full traceback
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\user\OneDrive\���������\STARVELL\cogs\on_interaction.py", line 421, in on_interaction
    await interaction.response.send_message("�������� ��������� � ���� ����", ephemeral=True, view=UsersSelect(self.bot))
                                                                                                   ^^^^^^^^^^^^^^^^^^^^^
  File "c:\Users\user\OneDrive\���������\STARVELL\cogs\selects.py", line 315, in __init__
    self.add_item(self.select)
  File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 287, in add_item
    raise TypeError(f"expected Item not {item.__class__!r}")
TypeError: expected Item not <class 'function'>```
#

also to create User select use this py select = ui.Select(..., type=ComponentType.user_select) i guess

buoyant quail
#

Looks like your self.select is a function

buoyant quail
slate swan
#

didnt see that

#

yea cause you are currently using a decorator not a class to create it

#

hence it returns a function

slate swan
#

so its pycord?

buoyant quail
slate swan
buoyant quail
#

ah

slate swan
slate swan
slate swan
#

Thanks!

upbeat mason
#

guys whats the website to upload code to

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

upbeat mason
#

ty

#

https://paste.pythondiscord.com/IPPA

okay so basically this is a help command, it has interactions such as buttons which work fine but theres a dropdown and for whatever reason it gives an interaction error with no consol error

#

anyone??

final iron
upbeat mason
#

i just need to get the dropdown working

slate swan
#

!customhelp

unkempt canyonBOT
#
Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

upbeat mason
#

bro someone be useful 😭

final iron
#

We are

#

Nobody is paid here, you should be grateful to get help at all

turbid condor
#

Check this for dropdown

#

And also I'll suggest you should subclass the default help command rather than removing it and creating your own like pep 9001 compliance officer and Down suggested

lyric sigil
#

i have this problem with my code :

PS C:\Users\canai\Desktop\bots\Partins> & C:/Users/canai/AppData/Local/Programs/Python/Python311/python.exe c:/Users/canai/Desktop/bots/Partins/main_partins.py
Traceback (most recent call last):
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 39, in <module>
    owm = OWM(owm_api_key)
              ^^^^^^^^^^^
NameError: name 'owm_api_key' is not defined
#
def run_bot():
    # Loading the Discord / OW Authentication (TOKEN/KEY) with dotenv 
    load_dotenv()
    owm_api_key = os.getenv('OWM_API')
    discord_token = os.getenv('TOKEN')


#Bot Setup
owm = OWM(owm_api_key)
intents = discord.Intents.all()
client = commands.Bot(command_prefix="/", intents=discord.Intents.all())
current_time = time.gmtime()
mgr = owm.weather_manager()

my code

quick brook
lyric sigil
quick brook
#

So no

lyric sigil
turbid condor
#

The key is inside the function

lyric sigil
#

this error but on my another window its working

turbid condor
#

Where as you are trying to access it from outside the function

quick brook
#

The key is scoped to the load func only. So it's unreachable in the main code

turbid condor
#

Now the whole code is in the function run_bot

#

That's why it's accessible

lyric sigil
#

Okay fixed it

turbid condor
lyric sigil
#

now i have this error

#
Traceback (most recent call last):
  File "c:\Users\canai\Desktop\bots\Partins\main_partins.py", line 46, in <module>
    @client.listen('on_message')
     ^^^^^^^^^^^^^
AttributeError: module 'discord.client' has no attribute 'listen'
#

i think i'm gonna blow up my pc

slate swan
#

listen is only for Bot

#

you have Client

turbid condor
#

You need to use event

lyric sigil
#

but if i use event its not gonna work

#

already had this problem be4

turbid condor
#

But I'll suggest switching to commands.Bot instead of discord.Client

#

That is way better then client and has more functionality

lyric sigil
#

so how do i fix the error ?

turbid condor
#

You read the above few messages i think i answered that

turbid condor
lyric sigil
slate swan
#

then move the code to one

#

or use Bot

turbid condor
#

Is the function name same?

lyric sigil
#

one for the mention of the bot and one for a blocked words system

#

and if i tried to use one of them it would just not working

slate swan
#

Client
Only possible to have 1 callback per event.

Bot
Possible to have multiple callbacks per even using listen decorators.

turbid condor
#

Yeah then you can either move the code to one or switch to Bot

lyric sigil
#

Already tried to move to one but didn't work

turbid condor
#

Tho switching is better

slate swan
slate swan
glad cradle
#

another reason to switch to disnake!

slate swan
glad cradle
#

facts are hard to accept ik

slate swan
#

nextcord is staying with me forever

glad cradle
#

bbbbbbbbruh

#

nextcord doesn't support yet nextcord.File for nextcord.Embed.set_image

quick brook
glad cradle
#

dpy has less features

slate swan
quick brook
#

Both also have lower quality of code and sometimes poor management

#

I see no point in continuing to use them

glad cradle
#

have you actually analized the source code? dpy has a lot of inefficiency too, just like how the Interaction System is implemented

slate swan
#

only point to use them is so not use discord.py app commands

quick brook
glad cradle
slate swan
#

t.Any

quick brook
glad cradle
quick brook
shrewd apex
glad cradle
glad cradle
quick brook
glad cradle
#

tf

quick brook
#

Forked dpy 1.7.3 and pretty much all of the implemented interactions in the same way

shrewd apex
#

serious discord bot debate time

slate swan
#

i was using discord.py then it suddenly stoped development and tried to use those discord_slash etc but it was so bad i moved to nextcord and im staying with it till today im just used to it

glad cradle
glad cradle
shrewd apex
slate swan
#

does it really matter that much

shrewd apex
slate swan
#

we're all gonna cease to exist soon enough anyway

glad cradle
slate swan
glad cradle
shrewd apex
slate swan
#

true (i prefer it over the other forks)

glad cradle
#

have you ever used one of them

slate swan
#

as long as you guys aren't using discord_slash or those other goofy 3rd party libraries

quick brook
#

Nonetheless, all of the forks do pretty much exactly the same thing as each other, and dpy already is the de-facto standard and has the power over the other forks

glad cradle
quick brook
#

So hence why pretty much all of the dpy forks are useless

glad cradle
quick brook
#

The only reason to continue using them is if you have bots written during the hiatus period

glad cradle
#

you're just talking knowing the base API that is in common with d.py

glad cradle
#

well that's your point, i can assure you that the forks have a lot of original and useful features which d.py doesn't have

shrewd apex
#

there a bunch of differences bw dpy and disnake on more of a developer level interface with newer features and api

shrewd apex
#

and incremental changes being applied on older ones

#

atleast with respect to disnake

glad cradle
final iron
#

List them

glad cradle
#

i can link the docs

final iron
#

Sure, if you list the specific events

slate swan
#

🗿

final iron
#

If you know that disnake has more and they’re better, you should know at least a couple events

shrewd apex
#

disnake has hot reloading for cogs

#

out of the box support

glad cradle
#

can't remember, lemme link them

shrewd apex
#

for events there are a bunch of lower level apis or triggers in main bot class that i have found useful just never matched and checked if it exists in dpy

glad cradle
slate swan
#

on_button_click joeCollapse

shrewd apex
glad cradle
glad cradle
slate swan
#

!pypi nextcord GIGACHAD

unkempt canyonBOT
glad cradle
#

they're called low level components

#

in d.py you can send components only using views

slate swan
#

!pypi disnake

unkempt canyonBOT
glad cradle
#

in disnake you can send raw components

#

there's also an extension for that which is really cool

glad cradle
slate swan
#

scared

shrewd apex
slate swan
#

does disnake really doesnt have Interaction.send method

shrewd apex
#

it does

glad cradle
slate swan
shrewd apex
#

skill issue 😔

unkempt canyonBOT
#

examples/interactions/localizations.py line 68

await inter.send(f"max: {data}")```
slate swan
#

Disnake:
Downloads last month: 54,912

Nextcord:
Downloads last month: 225,859

Discord.py:
Downloads last month: 9,663,717

glad cradle
#

why y'all talk without checking 😭

slate swan
#

im talking about examples on pypi page

glad cradle
#

ah

shrewd apex
#

dpy supermacy

glad cradle
#

it's because it was the only one

#

it's living from past glory

slate swan
#

aint now way

#

how is that 233k

final iron
#

Biggest cappers fr

slate swan
#

literally 687 downloads

glad cradle
slate swan
#

did they just start with 5.x or sum

#

and why is that april 10 this year

#

nah they did have 1.0

quick brook
#

on_button_clicked on dpy is simply called the callback coro

#

on_modal_submit is simply called on_submit within discord.ui.Modal

#

one thing disnake doesn't have is setup hooks

#

and with dpy, discord.Client (and by extension commands.Bot) are also async ctx managers, so you can just async with MyBot() as bot and also use other async ctx managers alongside it

#

and according to pepy.tech, here are the download results within the last 7 days:

Interactions.py: 482
Hikari: 3,306
Disnake: 10,989
Pycord: 12,574
Nextcord: 54,412
Discord.py: 1,822,157

#

so clearly dpy is better

slate swan
#

i wouldnt say its better just cause more people download it

glad cradle
#

why you're using the downloads as argument

quick brook
glad cradle
quick brook
glad cradle
glad cradle
quick brook
#

the stats show it

glad cradle
#

yeah past glory

slate swan
#

only reason that discord.py has so much is cause its interpreted as "main" library

upbeat mason
#

i have the regular emojis there but they dont show the emoji like dice_1 but as :dice_1

vapid parcel
#

Does someone wanna help me with a ban command?

#

I have it to where it tries to send a message to the user before banning, but if it doesnt have permission to ban the user it wont send the dm, but now when it does ban them it just wont send the dm at all

#
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member = None, *, reason=None):
    if member is None:
        error_embed = discord.Embed(
            title="Error",
            description="Please mention a member to ban.",
            color=0xFF0000
        )
        await ctx.send(embed=error_embed)
        return

    try:
        await member.ban(reason=reason)
        if ctx.guild.me.guild_permissions.send_messages:
            try:
                await member.send(f'You have been banned from {ctx.guild.name}. Reason: {reason}. By {ctx.author.mention}.')
            except discord.Forbidden:
                error_embed = discord.Embed(
                    title="Error",
                    description=f"Unable to send a ban message to {member.mention}'s DMs.",
                    color=0xFF0000
                )
                await ctx.send(embed=error_embed)
        ban_embed = discord.Embed(
            title="Banned",
            description=f'{member.mention} has been banned from this server. Reason: {reason}.',
            color=0x00FF00
        )
        await ctx.send(embed=ban_embed)
    except discord.Forbidden:
        error_embed = discord.Embed(
            title="Error",
            description=f"Missing permissions to ban {member.mention}.",
            color=0xFF0000
        )
        await ctx.send(embed=error_embed)```
queen swallow
#

Hello am doing my 1st project (discord bot for dnd) I want the bot to pull spell or class information in command, i dont know how to ( am pretty new to coding)

#

(am just finish making welcome command to new people to sever)

slate swan
#

The library is not made for people that are "pretty new to coding" but rather for people with advanced knowledge

vapid parcel
slate swan
upbeat mason
slate swan
#

Because your bot is not in this server smart

#

So it can't use emojis of servers it's not in

#

And to get the ID just send \:whatever:

slate swan
#

we cant help you with getting your bot here its most likely impossible

vapid parcel
#

huh

slate swan
#

but you can download the emojis and upload to your own server

queen swallow
#

What do you recommend 1st thing to learn for my project?

vapid parcel
slate swan
slate swan
slate swan
#

why dont you move the error handling into error handler

unkempt canyonBOT
#
Resources

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

queen swallow
#

thank you

vapid parcel
slate swan
vapid parcel
#

okay what else is wrong with the command besides error handling?

slate swan
#

i dont know its too messy thats why i recommend to use error handler

#

then you will most likely see why it wont send the dm

vapid parcel
#

Okay

slate swan
#

currently you have try excepts inside try excepts

buoyant quail
glad cradle
#

all these people are most likely following outdated news, guides and tutorials, that's the cause of these numbers

slate swan
#

most likely

glad cradle
gloomy bone
#

can someone help me i made a discord bot but i dont know how to bring it online

thin raft
gloomy bone
gloomy bone
thin raft
#

but we wotn help on ai written code

gloomy bone
#

y not?

thin raft
#

because we're not helping you

#

we're doing the job for you

gloomy bone
thin raft
#

learn python and we will help you

scarlet aurora
#

send it in a code block

gloomy bone
#

can just send the file in dms

gloomy bone
# scarlet aurora send it in a code block

`import imaplib
import email
import discord
import schedule
import time

Discord Bot Token

TOKEN = 'MTE1MDYyjzMg.GsD_94.QNtCQqUkKR8dR5hDF8g2VuPZaXwuLeQoVErgxY'

Discord Server ID and Channel ID

SERVER_ID = '6740788621955290' # Replace with your Discord server ID
CHANNEL_ID = '1150514352827408404' # Replace with your Discord channel ID

Gmail IMAP Email Settings

IMAP_SERVER = 'imap.gmail.com' # IMAP server address for Gmail
IMAP_PORT = 993 # IMAP server port for secure connection
EMAIL_ADDRESS = '@gmail.com' # Your Gmail email address
EMAIL_PASSWORD = 'jbhnnwoueiiai' # Your Gmail password

Function to send a message to Discord

async def send_discord_message(content):
intents = discord.Intents.default()
intents.typing = False
intents.presences = False

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    server = client.get_guild(int(SERVER_ID))
    channel = server.get_channel(int(CHANNEL_ID))
    await channel.send(content)
    await client.close()

await client.start(TOKEN)

Function to check email

async def check_email():
try:
print("Script started") # Add this line for verification
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
mail.select("inbox")
result, data = mail.search(None, "UNSEEN")

    if result == "OK":
        email_ids = data[0].split()
        for email_id in email_ids:
            result, email_data = mail.fetch(email_id, "(RFC822)")
            if result == "OK":
                raw_email = email_data[0][1]
                email_message = email.message_from_bytes(raw_email)

                if (
                    email_message["From"] == "alert@uptimerobot.com" or
                    "uptimerobot" in email_message.get_payload().lower()
                ):
                    subject = email_message["Subject"]
                    await send_discord_message(f"New email from {email_message['From']} with subject: {subject}")
except Exception as e:
    print(f"An error occurred: {str(e)}")
finally:
    mail.logout()

Schedule email checking every 5 minutes

schedule.every(5).minutes.do(check_email)

if name == "main":
while True:
schedule.run_pending()
time.sleep(1)
`

#

i editted the token etc so its not public

mighty pilot
#

can i store an interaction object in a list or set then pull it later and use info from it?

onyx elk
#

anyone wanna add my bot to their server, yk help me get verified

mighty pilot
#

if they did, they would

tall wharf
#

I'm trying to create my first bot, but I'm running into some issues as it is my first time using Python on a Windows computer and don't know how to properly set it up properly

tall wharf
#

not working either, hold on

onyx elk
#

i do that

slate swan
#
async def send_message_with_buttons(ctx):
    try:
        # Create buttons
        button1 = Button(style=discord.ButtonStyle.primary, label="Button 1", custom_id="button_1")
        button2 = Button(style=discord.ButtonStyle.secondary, label="Button 2", custom_id="button_2")
        button3 = Button(style=discord.ButtonStyle.danger, label="Button 3", custom_id="button_3")

        
        view = View()
        view.add_item(button1)
        view.add_item(button2)
        view.add_item(button3)

        # Send a message with the buttons and view
        await ctx.send("Here are some buttons:", view=view)
    except Exception as e:
        logger.error(f"An error occurred while sending buttons: {e}")

@bot.event
async def on_button_click(interaction):
    try:
        if interaction.custom_id == "button_1":
            await interaction.respond(content="Button 1 was clicked!")
        elif interaction.custom_id == "button_2":
            await interaction.respond(content="Button 2 was clicked!")
        elif interaction.custom_id == "button_3":
            await interaction.respond(content="Button 3 was clicked!")
    except Exception as e:
        logger.error(f"An error occurred during button interaction: {e}")```

everytime i press a button i get interaction failed? how do i fix it
#

ive looked over my code many times

unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

hushed galleon
#

what library are you using? if its discord.py, on_button_click isnt an event that's used

slate swan
onyx elk
#

idk this help u

hushed galleon
# slate swan i am using discord.py, that event would it be then/

buttons and views work with callbacks, typically written either as a subclass of [View: ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Button 1")
async def button_1(self, interaction, button):
# interaction.respond() is not a thing in discord.py
await interaction.response.send_message("Hello world!")

Usage:

view = MyView()
await channel.send(..., view=view)or a subclass of Button:py
class Button1(discord.ui.Button):
async def callback(self, interaction):
await interaction.response.send_message("Hello world!")

Usage:

view = discord.ui.View()
view.add_item(Button1(label="Button 1"))
await channel.send(..., view=view)``` see also the official examples: https://github.com/Rapptz/discord.py/tree/v2.3.2/examples/views

onyx elk
#

heres example for buttons

hushed galleon
hushed galleon
slate swan
#
    async def menu1(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.response.send_message("Worked Boss")
        workbook = openpyxl.load_workbook(excel_file)
        worksheet = workbook.active
        worksheet.append([response])
        workbook.save(excel_file)```

how can i add the response variable
mighty pilot
mighty pilot
pallid meadow
#

Depends, if you want user text input you would make another argument in the function and type hint it with :str

#

Oh wait this is a button KEKW

#

Then yeah, I’m also having trouble understanding the question

quick brook
#

just use a db

mighty pilot
#

I don't even ask anymore. If people want to use it I let them lol

queen swallow
#

is discord bot too much of project for beginner?

quick brook
#

dpy is a highly advanced library

#
- Primitive data types
- Operators
- Data structures
- Importing
- Variables, namespace and scope
- String formatting
- OOP
- Control flow
- Exception handling
- Function definitions
- Classes, objects, attributes and methods
- Console usage, interpreters and environments
- Decorators

Useful to know:
- Asyncio basics
- What is blocking?
- Logging
- knowing how to read docs properly
``` for more details see <https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#required-knowledge>
#

You should know these concepts before you get started

quick brook
#

see tag above for the concepts you'll need to know beforehand

#

once you know and fully understand these concepts, you can continue with getting started

#
  1. Before even attempting to create a discord bot, please learn python (?tag lp)
  2. To install discord.py, please run python3 -m pip install discord.py (linux), or py -3 - m pip install discord.py (windows)
    If you wish to use voice functionality, please use discord.py[voice] instead of discord.py
  3. Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
  4. When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
    or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
  5. The library documentation is available at https://discordpy.readthedocs.org/en/latest/

If you need help please make a post in our #985299059441025044 Forum if its related to Python and/or Discord.py

If you are migrating from the old version of this library (1.7.x) to version 2.X.X please follow the migrating guide https://discordpy.readthedocs.io/en/latest/migrating.html

queen swallow
#

thank you

hushed galleon
# queen swallow is discord bot too much of project for beginner?

i wouldn't say you need to fully understand every concept listed, but object oriented programming is definitely a big aspect of discord.py as it uses a lot of objects to let you do stuff with your bot, and the documentation's API reference is stuffed with classes, attributes, and methods that are hard to grasp without knowing their distinctions (though this is not to say you should start learning OOP before more primitive concepts like variables and functions, since these concepts build on top of each other)

as for resources, discord.py can be quite hard to learn from the internet alone (most youtube videos and stackoverflow posts have gotten very out-of-date), but you can find plenty of learning materials for python itself like the official tutorial, Automate The Boring Stuff, and Corey Schafer (see his beginner and OOP playlists)

regardless of what you know, getting used to a library can take some time, so start off simple with your bots and gradually work towards more complex features

queen swallow
#

I do watch some video and each different make me confuse which right

quick brook
#

Such as... leaking tokens, no message contents, and so forth

turbid condor
gloomy bone
#

can someone give me recommendations on this code on what to improve on im trying to make a discord bot read my detect a email/specific word import
`asyncio
import discord
from aioimaplib import aioImap4

Define your Discord bot token and email credentials

DISCORD_TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
EMAIL_HOST = 'YOUR_EMAIL_HOST'
EMAIL_PORT = 993
EMAIL_USERNAME = 'YOUR_EMAIL_USERNAME'
EMAIL_PASSWORD = 'YOUR_EMAIL_PASSWORD'
TARGET_EMAIL = 'TARGET_EMAIL_ADDRESS'
TARGET_WORD = 'TARGET_WORD'

Initialize the Discord client and IMAP client

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
imap_client = aioImap4(EMAIL_HOST, EMAIL_PORT)

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

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

# Check if the message contains the target word
if TARGET_WORD.lower() in message.content.lower():
    # Send a Discord notification
    await message.channel.send("Received a message with the target word!")

async def check_emails():
await client.wait_until_ready()
while not client.is_closed():
try:
# Connect to the email server
await imap_client.wait_hello()
await imap_client.login(EMAIL_USERNAME, EMAIL_PASSWORD)

        # Select the mailbox (e.g., INBOX)
        await imap_client.select('INBOX')

        # Search for emails containing the target word or from the target email
        result, data = await imap_client.search(None, f'(FROM "{TARGET_EMAIL}" OR TEXT "{TARGET_WORD}")')

        # Fetch and process the matching emails
        for num in data[0].split():
            _, email_data = await imap_client.fetch(num, '(BODY[TEXT])')
            email_content = email_data[0][1].decode('utf-8')
            print(f"Received email:\n{email_content}")

            # Send a Discord notification
            channel = client.get_channel(YOUR_DISCORD_CHANNEL_ID)  # Replace with your Discord channel ID
            await channel.send(f"Received an email:\n{email_content}")

    except Exception as e:
        print(f"Error checking email: {str(e)}")

    # Wait for some time before checking again
    await asyncio.sleep(60)  # Check every minute

Start the email checking loop and the Discord bot

client.loop.create_task(check_emails())
client.run(DISCORD_TOKEN) `

hasty pike
#

@gloomy bone can you use ``` 3 for better view?

quick brook
#

!codeblocks

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.

hasty pike
#

@quick brook can you help me with select menu

hasty pike
quick brook
hasty pike
#

How can we reset these selections after user is done with interaction?

gloomy bone
# quick brook Again, do u know what codeblocks are
import discord
from aioimaplib import aioImap4

# Define your Discord bot token and email credentials
DISCORD_TOKEN = 'YOUR_DISCORD_BOT_TOKEN'
EMAIL_HOST = 'YOUR_EMAIL_HOST'
EMAIL_PORT = 993
EMAIL_USERNAME = 'YOUR_EMAIL_USERNAME'
EMAIL_PASSWORD = 'YOUR_EMAIL_PASSWORD'
TARGET_EMAIL = 'TARGET_EMAIL_ADDRESS'
TARGET_WORD = 'TARGET_WORD'

# Initialize the Discord client and IMAP client
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
imap_client = aioImap4(EMAIL_HOST, EMAIL_PORT)

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

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

    # Check if the message contains the target word
    if TARGET_WORD.lower() in message.content.lower():
        # Send a Discord notification
        await message.channel.send("Received a message with the target word!")

async def check_emails():
    await client.wait_until_ready()
    while not client.is_closed():
        try:
            # Connect to the email server
            await imap_client.wait_hello()
            await imap_client.login(EMAIL_USERNAME, EMAIL_PASSWORD)

            # Select the mailbox (e.g., INBOX)
            await imap_client.select('INBOX')

            # Search for emails containing the target word or from the target email
            result, data = await imap_client.search(None, f'(FROM "{TARGET_EMAIL}" OR TEXT "{TARGET_WORD}")')

            # Fetch and process the matching emails
            for num in data[0].split():
                _, email_data = await imap_client.fetch(num, '(BODY[TEXT])')
                email_content = email_data[0][1].decode('utf-8')
                print(f"Received email:\n{email_content}")

                # Send a Discord notification
                channel = client.get_channel(YOUR_DISCORD_CHANNEL_ID)  # Replace with your Discord channel ID
                await channel.send(f"Received an email:\n{email_content}")

        except Exception as e:
            print(f"Error checking email: {str(e)}")

        # Wait for some time before checking again
        await asyncio.sleep(60)  # Check every minute

# Start the email checking loop and the Discord bot
client.loop.create_task(check_emails())
client.run(DISCORD_TOKEN) ```sorry
hasty pike
#

@gloomy bone and what's the issue?

hasty pike
gloomy bone
quick brook
gloomy bone
hasty pike
hasty pike
gloomy bone
turbid condor
turbid condor
# gloomy bone ```asyncio import discord from aioimaplib import aioImap4 # Define your Discord...

Welp there are a two things that u can do

  • Store the variables in a different file like use a config.py or .env instead of of the main.py.
  • Use commands.Bot instead of discord.Client as Bot is better since provides more functionality (in case you want to make the bot bigger)

Now as for a mistake you are missing meesage_content intent which is required to read messages so your on_message event will not work as intended. Check !intents for further info.

gloomy bone
# turbid condor Welp there are a two things that u can do - Store the variables in a different f...

ty also do u mind taking a look about this one import discord

from aioimaplib import aioImap4
from discord.ext import commands
from config import DISCORD_TOKEN, EMAIL_HOST, EMAIL_PORT, EMAIL_USERNAME, EMAIL_PASSWORD, TARGET_EMAIL, TARGET_WORD, DISCORD_CHANNEL_ID

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True  # Enable reading message content

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

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

@bot.command()
async def hello(ctx):
    await ctx.send('Hello!')

@bot.command()
async def say(ctx, *, message):
    await ctx.send(message)

@bot.event
async def on_message(message):
    await bot.process_commands(message)  # Process commands alongside custom on_message code
    if message.author == bot.user:
        return
    # Access the content of the message using message.content
    message_content = message.content
    # Check if the message contains the target word
    if TARGET_WORD.lower() in message_content.lower():
        # Send a Discord notification
        await message.channel.send("Received a message with the target word!")

async def check_emails():
    await bot.wait_until_ready()
    while not bot.is_closed():
        try:
            # Connect to the email server
            await imap_client.wait_hello()
            await imap_client.login(EMAIL_USERNAME, EMAIL_PASSWORD)
            # Select the mailbox (e.g., INBOX)
            await imap_client.select('INBOX')
            # Search for emails containing the target word or from the target email
            result, data = await imap_client.search(None, f'(FROM "{TARGET_EMAIL}" OR TEXT "{TARGET_WORD}")')
            # Fetch and process the matching emails
            for num in data[0].split():
                _, email_data = await imap_client.fetch(num, '(BODY[TEXT])')
                email_content = email_data[0][1].decode('utf-8')
                print(f"Received email:\n{email_content}")
                # Send a Discord notification
                channel = bot.get_channel(DISCORD_CHANNEL_ID)
                await channel.send(f"Received an email:\n{email_content}")
        except Exception as e:
            print(f"Error checking email: {str(e)}")
        # Wait for some time before checking again
        await asyncio.sleep(60)  # Check every minute

# Start the email checking loop and the Discord bot
bot.loop.create_task(check_emails())
bot.run(DISCORD_TOKEN)
turbid condor
#

You forgot process commands in your on_message event which will cause your commands to not work

#

Instead of @bot.event use @bot.listen() to solve the above stated issue

gloomy bone
turbid condor
#

Might be linter issue

gloomy bone
turbid condor
#

The thing that colors your code

#

And finds out error

gloomy bone
#

so is it important

turbid condor
#

Nah if your code is working fine then ignore it

#

And don't use spaces when naming your files instead use an underscore where you need a space

gloomy bone
#

and do you know what going on

#

i typed in the email and i did the pass right

turbid condor
#

Welp the error says they are invalid

gloomy bone
turbid condor
#

Someone will reply and you will get better suggestions

gloomy bone
#

okay i got you thanks again and goodnight

slate swan
#

Are any of the raspberry pis capable of running large discord bots?

quick brook
#

just get a vps and use that instead

slate swan
#

where's the docs for d.py slash commands

naive briar
unkempt canyonBOT
#

class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
quick brook
quick brook
# slate swan where's the docs for d.py slash commands

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.

#

Nanika is writing an official app commands guide and I will also be helping with that

#

Gonna help her review the docs. Already have been reviewing another doc entry for the last couple of days

slate swan
#

is there a limit on app_command choices per command?

hushed galleon
unkempt canyonBOT
#

discord/app_commands/commands.py lines 2205 to 2211

if isinstance(inner, Command):
    _populate_choices(inner._params, parameters)
else:
    try:
        inner.__discord_app_commands_param_choices__.update(parameters)  # type: ignore # Runtime attribute access
    except AttributeError:
        inner.__discord_app_commands_param_choices__ = parameters  # type: ignore # Runtime attribute assignment```
hushed galleon
slate swan
#

I mean like the actual amount of choices you can put

quick brook
#

Don't remember

slate swan
#

I think it's 25 yeah

quick brook
slate swan
#

auto completes?

quick brook
# slate swan auto completes?

Autocomplete is an interaction type that shows a set autocomplete values/options to the user as they type in an option.
Autocomplete is only available for str, int, and float types, and only available in chat-input (slash) commands.

To add an autocomplete option to a command, it is recommended for it to be done in one of two ways:

You can use the @command.autocomplete('option_name') decorator, where the str argument passed as the first parameter to the decorator
is the name of the parameter you want to provide autocomplete to:

@app_commands.command(...)
async def foo(interaction: discord.Interaction, bar: str):
    ...

@foo.autocomplete('bar')
async def autocomplete_callback(interaction: discord.Interaction, current: str):
    # Do stuff with the "current" parameter, e.g. querying it search results...

    # Then return a list of app_commands.Choice
    return [
        app_commands.Choice(name='Option 1', value='Option 1')
    ]

As seen above, the parameters in autocomplete_callback are interaction (the autocomplete interaction received) and current (the incomplete value the user is entering).

You can also use it as @app_commands.autocomplete(option_name=callback). Every kwarg name is the option name and the value of it is the function/callback of the autocomplete callback, taking and returning the same exact arguments as above.

TODO: Autocomplete example not in master branch
Documentation:
https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete
https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.autocomplete

naive briar
tall wharf
#

ok, Imma ask here since I'm currently working on a discord bot.

quick brook
naive briar
quick brook
naive briar
#

They asked for the docs

quick brook
#

one person please

tall wharf
#

For some reason my pip install isn't working, so I googled a solution. On a website they told me to run the python -v command in the command prompt to see what version of python I'm running. My computer told me that I don't have python installed even though I installed it yesterday. what the hell am I doing wrong here?

tall wharf
#

yup

#

I also have all the files on the computer

quick brook
#

probably not in PATH

tall wharf
#

ok, how do I fix that?

quick brook
#

for adding to system path on windows, you can google that up

tall wharf
#

alright, thank you

quick brook
#

np

slate swan
#

So I have a question... In one of my js bots the dir is setup like this:

bot/commands
bot/hooks

What would be the simpliest way to in the commands dir to have like test.py and it is the /test command. I can do whatever in the main file.

I am using py-cord, just referrencing a js bot that I have.

tall wharf
# quick brook np

so, small issue. I found pip, but I don't have a python.exe file. do I need to reinstall python?

quick brook
tall wharf
#

alright

slate swan
# quick brook cogs

What would be the most effective away then doing like:

class Test(commands.Cog):
  def __init__(self, bot) -> None:
    self.bot = bot

  @commands.slash_command(name="test", description="testing")
  async def _test(self, inter: discord.Interaction):
    await ctx.respond("Testing")

def setup(bot):
  bot.add_cog(Test(bot))
#

For every file ^^

quick brook
#

applying djs princples and design to dpy is like trying to shove a circle through an outline designed for squares only with both shapes constrained to the same sizes and specs

#

another example can be trying to make an orange into a banana

slate swan
quick brook
#

that's the point

#

anyways, if you need examples on cogs on an actual bot, I would recommend looking into this

tall wharf
#

happy to report that I fixed my python 😄

quick brook
tall wharf
#

pip is still giving me the middle finger

slate swan
#

hmmmm what discord bot should I make an open source....

quick brook
slate swan
quick brook
# slate swan Any ideas?

what i will say is this: do not reinvent the wheel. What i mean by this is most bots do exactly what other bots already do. and in fact, if there is an idea that you have, more than likely another bot already has done it

#

you'll notice that for example with birthday bots, there will be either a monoploy or oligopoly on said feature or idea

#

if you want a good bot, it must approach it from an angle that has not been approached from or solves an issue that has never been solved every

#

you can definitely analyze the discord bot market from a economics point of view. but i won't go on about analyzing market factors and mircoeconomics

hasty pike
#
      await interaction.response.edit_message(view=self)
await interaction.followup.response.send()

Can anyone help me with this

#

'webhook' object has no attribute 'response'

#

Error on 2nd line

golden portal
golden portal
#

no, interaction.followup is a webhook

hasty pike
#

What what do i need to do?

#

followup.send()

#

Worked

#

Thanks

golden portal
#

welcome

brazen raft
tall wharf
#

thanks, I managed to solve it though by reinstalling python though

#

I'll keep it in mind for the future though

onyx elk
slate swan
#

!d discord.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
onyx elk
#

class Buttons(discord.ui.View):
def init(self, *, timeout=180):
super().init(timeout=timeout)
@discord.ui.button(label="Button",style=discord.ButtonStyle.gray)
async def gray_button(self,button:discord.ui.Button,interaction:discord.Interaction):
await interaction.response.edit_message(content=f"I generated you: !")

@client.command()
async def button(ctx ):
await ctx.send("Click me to generate a number!",view=Buttons())

lyric sigil
#

I have a question , i want to create a webhook thats says if a change occured on a specific website. How do i make this ?

#

cuz i have this block :

import aiohttp
from discord.ext import tasks

RECENT_HTML = ""

@tasks.loop(hours=1)
async def download_webpage():
    async with aiohttp.ClientSession() as session:
        async with session.get("<url>") as response:
            if response.status != 200:
                # Notify users that the website could not be scraped

             html = await response.text()
            if html != RECENT_HTML:
                # Notify users of changes within the website
                # An HTML parser could be used to identify specific changes within the HTML
                # Or you could just tell the members that a change occurred.
             RECENT_HTML = html

But i can't figure out how to link it w/ a webhook

quick brook
lyric sigil
#

can you simplify that ?

slate swan
#

what do i do if all my slash commands are printing this?..

#

Delete that command you've created just to get the badge and add actual commands

#

what is the point of getting developer badge when you are not a developer?

mighty pilot
#

Is there some interactive walk through now or something?

quick brook
#

Clout apparently

shrewd apex
wicked atlas
slate swan
wicked atlas
#

?

slate swan
shrewd apex
#

maybe make the navbar transparent

#

or just remove it altogether

#

also ur scroll indicator and arrow buttons seem to be reversed

slate swan
#

bruh_what i kind of abandoned it

shrewd apex
#

i like the pics Shrug

gloomy bone
#

i made a code for discord to login my gmail and send me somehting if it recognizes it to my discord server5

#

but when i try to login it tells me theres a error

#

does any1 mind telling me why

mighty pilot
#

That sounds horrible lol

#

Was it going off frequently?

#

Idk if it affects login but the api will only take so many requests per day nvm it's usage per second not day

gloomy bone
# quick brook Why

y i made a discord bot to send men notification to my discord server if i recieved a message by a specific email/person?

#

is that what ur asking or u asking something else

mighty pilot
gloomy bone
#

ohh okay

mighty pilot
#

Sounds like a Google specific thing tbh

#

the Gmail API has a daily quota limit for sending emails. According to the Gmail API documentation, the daily sending quota is 1,000 messages per day for free Gmail accounts and 10,000 messages per day for paid G Suite accounts.

#

I doubt you're hitting those numbers

#

But they're a thing

quick brook
gloomy bone
#

i dont check my email and i only check my discord and the bots only gonna be used for me and no1 else

#

and i need to know when this certain email texts me

quick brook
#

just like storing messages sounds really sus

gloomy bone
#

and i dont check email thats it

quick brook
#

ok then

mighty pilot
quick brook
#

then it's a smtp / gmail thing

mighty pilot
#

I thought the same thing at first lol

gloomy bone
quick brook
#

idk about that so...

mighty pilot
#

Google would be a good place to start

gloomy bone
#

i used google

#

nothing on it that helps me

mighty pilot
#

There's a Google Dev discord server

#

I meant ask the Google community/people that are knowledgeable on the Google half of your program

gloomy bone
gloomy bone
#

that r actually active

mighty pilot
gloomy bone
#

there all just random stuff

mighty pilot
#

Idk

mighty pilot
#

Can I put multiple views in one class

upbeat gust
final iron
#

It’s not recommended though

cinder ledge
#

Anyone else using Vultr VPS with New Jersey server been seeing some weird latencies or timeout errors with their bot?

gloomy bone
#

someone tell me what this is

karmic nimbus
#
    @commands.command(hidden=True)
    async def join(self, ctx):
        # initialize node
        ...        
        vc = 0
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
        
    @commands.command(hidden=True)
    async def play(self, ctx, *, track: str):
        vc = 0
        vc: wavelink.Player = ctx.voice_client
        
        tracks = await wavelink.YouTubeTrack.search(track)
        
        if not tracks:
            await ctx.send("no track found")
            
        else:
            await vc.play(tracks[0])
            await ctx.send(f"Now playing: {tracks[0]}")

why no music played? it said now playing.
btw i use py-cord not dpy

vale wing
vale wing
vale wing
slate swan
#

when a bot is in voice can it only input or does it actually receive output too?

vale wing
slate swan
meager rock
#

Nope

quick brook
#

But... there is a PR in the works for it

meager rock
#

there's a pull request for that though, you can get some code from there and make your own implementation

#

that is ,if discord didn't break anything since then

quick brook
#

Plus an experimental ext that is worked on by Imayhaveborkedit

#

Note the keyword experimental

meager rock
#

Cool, there was another pr I'm aware of
Is this the continuation of the same repo?

slate swan
meager rock
quick brook
meager rock
#

makes sense
time to make one for hikari

quick brook
meager rock
cinder ledge
mighty pilot
pallid meadow
#

That’s why I always recommend people host their bots in an ashburn datacenter

#

I think there could other underlying issues with their code here I don’t think this would be a discord issue

cinder ledge
#

While I wouldn’t say I’m amazing at Python or d.py, probably the host. Reset the server and things have been running better. Still getting weird sporadic 404s though. Still looking up what exactly that may mean

cinder ledge
turbid condor
#

As far as i know 404 generally occurs when something isn't found

#

Can't say much without looking at your traceback

cinder ledge
#
[2023-09-13 08:19:14] [ERROR   ] discord.app_commands.tree: Ignoring exception in command 'wiki'
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "/root/FAE_main/cogs/Informative.py", line 131, in wiki
    await interaction.response.defer(thinking=True)
  File "/usr/local/lib/python3.10/dist-packages/discord/interactions.py", line 661, in defer
    await adapter.create_interaction_response(
  File "/usr/local/lib/python3.10/dist-packages/discord/webhook/async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/usr/local/lib/python3.10/dist-packages/discord/app_commands/commands.py", line 846, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'wiki' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
naive briar
#

You responded too late

turbid condor
#

Defer your interaction and the send a followup

cinder ledge
#

I thought that's what defer was for?

naive briar
#

They got the error while trying to defer

cinder ledge
#
    @app_commands.command(name='wiki',description='Share campaign details in wiki format!')
    async def wiki(self, interaction: discord.Interaction, campaign: str = None):
        await interaction.response.defer(thinking=True)

        if campaign is None:
            campdata = await Tome.fetch(f"""SELECT campaign_key, campaign_name, camp_desc
                                            FROM campaigns 
                                            WHERE registered_id = {interaction.user.id} 
                                                    AND guild_id = {interaction.guild.id}""")
            campkey = campdata[0]['campaign_key']
            if len(campkey) == 0:
                await interaction.followup.send(f"It doesn't look like you're running a campaign, please specificy campaign name or create one with /start campaign!")
                return
        else:
            campdata = await Tome.fetch(f"""SELECT campaign_key, campaign_name, camp_desc 
                                            FROM campaigns 
                                            WHERE guild_id = {interaction.guild.id} 
                                                    AND campaign_name = $1""", campaign)
            campkey = campdata[0]['campaign_key']
            if len(campdata) == 0:
                await interaction.followup.send(f"Could not find campaign: {campaign}. Check spelling and case sensitivity")
                return
                
        data = await Tome.fetch(f"""SELECT w.world_name, w.world_desc, l.location_name, l.location_description, n.npc_name, n.npc_description
                                FROM campaigns c
                                LEFT JOIN worlds w ON c.campaign_key = w.campaign_key
                                LEFT JOIN locations l ON w.world_id = l.world_id
                                LEFT JOIN non_play_char n ON l.location_key = n.location_key
                                WHERE c.campaign_key = '{campkey}'""")

        base = wCampaign(title=campdata[0]['campaign_name'],description=campdata[0]['camp_desc'])
        await base.generate(data)

        await interaction.followup.send(embed=base,view=WikiView(camp=campdata,data=data))```
#

my wiki command starts with defer

#

sometimes, when the command works, you'll see the "is thinking.." prompt.
Other times, it just doesn't respond and the log gives 404

#

my bot.latency also shows anwhere between 30ms to > 3k ms, but that's been steady since I reset the server

turbid condor
#

Can't say for sure but it might be a issue on the host par

#

Yeah I'd say a latency between 30-200 might be good

#

Try checking the code by running on your own system and see if the problem continues

naive briar
#

That explains the error

turbid condor
#

Even a latency of 300+ is no good

cinder ledge
#

It was stupid

turbid condor
turbid condor
#

Switch to a better host

cinder ledge
turbid condor
#

!hosting

unkempt canyonBOT
#
Discord Bot Hosting

Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.

See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.

You may also use #965291480992321536 to discuss different discord bot hosting options.

obtuse saddle
#

im doing a bot

#

and I keep getting this error for a kick commmand

#
ValueError: Callback SlashApplicationCommand kick <function kick at 0x0000023E5EEA9B20> is missing the interaction parameter. Please double check your function definition```
#
@bot.slash_command()
async def kick(interaction: nextcord.Interaction, user: nextcord.Member, reason: str):
    if not interaction.user.guild.permissions.administrator:
        await interaction.response.send_message("You do not have permission to run this command, permission needed = ADMINISTRATOR.", ephemeral=True)

    else:
        await interaction.response.send_message(f"Kicked (user.mention)", ephemeral=True)
        await user.kick(reason=reason)
#

is my code

slate swan
#

full traceback?

onyx elk
#

can i make a full discord bot using every single code i find in this channel

sick birch
#

maybe

buoyant quail
#

i believe yes

#

depending on what "full" bot means

turbid condor
onyx elk
final iron
onyx elk
final iron
#

No

#

What’s it called

onyx elk
#

but pls use my referal link if u wanna check out

#

i need the coins (u dont need referals but it n

#

makes ut easier to get better sercers

slate swan
#

is that an ad 🧐

final iron
#

Also what’s the point of creating a kick command when it already exists

#

Using the built in function has many, many more advantages

naive briar
#

Like?

slate swan
#

You can extend upon the built-in commands with your own functionality, so making a custom kick command can be useful I suppose

naive briar
#

How?

final iron
# naive briar Like?

Considering role hierarchy, permissions, 2FA server security settings, audit log and UI

naive briar
#

What does audit log and UI have to do with kick commands?

final iron
#

Who user who performed the kick will show up in the audit log, and can actually be filtered for

naive briar
#

And you can check the user's permissions before letting them kicking an user ducky_sphere

final iron
#

Sure, but he’s only checking for administrator

#

Kicking a user also has a UI, furthermore relying on bots to perform these built in actions makes no sense

naive briar
#

Nice

turbid condor
#

Welp those are in built commands so they obv have advantage over the bot commands

final iron
#

Okay, so why use bot commands lol

naive briar
#

More commands to make a million commands Discord bot ducky_wizard

obtuse saddle
obtuse saddle
obtuse saddle
final iron
obtuse saddle
#

Im doing an edited version with like my edits

quick brook
# obtuse saddle Alr

they are highly outdated, contain bad practices, and most of the time, only focus on doing it in one way only

obtuse saddle
#

A question

#

So the tutorial does suck.

#

Im using it for a basic understanding

#

I am stuck on something.

quick brook
obtuse saddle
#

For this command ```py
@bot.slash_command(description="kicks a user from the designated server.")

obtuse saddle
#

I need to add something which checks the guilds

#

that the command is run in

quick brook
obtuse saddle
#

No,

#

Checks what guild the command was used in

quick brook
obtuse saddle
#

interaction.guild?

#

So how would I fit it in?

quick brook
#

or if you want to only allow that command to be ran on those guilds only, then this would be what you want to look for

obtuse saddle
#
@bot.slash_command(description="kicks a user from the designated server.", guild_ids=interaction.guild)
quick brook
obtuse saddle
#

Idk

quick brook
serene pasture
#

Hi

obtuse saddle
#

No-

quick brook
#

nonetheless, just go ask on nextcord server bc i dont work with nextcord and refuse to

obtuse saddle
#

So what do you work with?

quick brook
slate swan
obtuse saddle
slate swan
#

just let people use what they want

obtuse saddle
#

No nextcord chat sucks

#

It aint active

slate swan
#

what is your question?

obtuse saddle
#

My question is.

#

I need to add something which checks the guild id.

#

That the command is run in.

slate swan
#

you want a command be only available in one guild?

obtuse saddle
#

No.

slate swan
#

you want to do some special action for desired guild?

obtuse saddle
#

???

slate swan
#

i dont know explain more

obtuse saddle
#

Alright

#

So In the beggining of my command

#
@bot.slash_command(description="kicks a user from the designated server.", guild_ids = # I need a guild id here.
glad cradle
#

they're called modals

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
obtuse saddle
#

You know what

slate swan
quick brook
slate swan
#

(this restricts command to only guilds selected)

glad cradle
slate swan
#

like i said

obtuse saddle
#

Well it doesn't work without it

slate swan
#

it can take some time to sync globally

obtuse saddle
#

Discord.py time, Idk what the hell im doing lemme go watch a 30 minute tut.

slate swan
#

dont watch tutorials on youtube

quick brook
#

if you even need some help, even with getting started with dpy, i would recommend joining the server

slate swan
#

they are so bad

glad cradle
#

i mean if you aren't even able to get the guild id you think syncing the command tree will be easier?

obtuse saddle
#

Where do I get a tutorial then?

slate swan
quick brook
# obtuse saddle Where do I get a tutorial then?
  1. Before even attempting to create a discord bot, please learn python (?tag lp)
  2. To install discord.py, please run python3 -m pip install discord.py (linux), or py -3 - m pip install discord.py (windows)
    If you wish to use voice functionality, please use discord.py[voice] instead of discord.py
  3. Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
  4. When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
    or if you wanna use slash commands: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
  5. The library documentation is available at https://discordpy.readthedocs.org/en/latest/

If you need help please make a post in our #985299059441025044 Forum if its related to Python and/or Discord.py

If you are migrating from the old version of this library (1.7.x) to version 2.X.X please follow the migrating guide https://discordpy.readthedocs.io/en/latest/migrating.html

#

best one

obtuse saddle
#

?tag lp

novel apexBOT
#

This is not a Modmail thread.

quick brook
obtuse saddle
#

Im going to first full learn python

slate swan
#

gl switching libraries mid project xd

slate swan
quick brook
glad cradle
obtuse saddle
#

I was watching a yt tut LOL

bright heron
#

sup guys can any1 help me?

quick brook
bright heron
#

wait im sending ss

#

@quick brook

quick brook
bright heron
#

ye but idk how i fix it

#

im kinda dumb tbh

quick brook
slate swan
#

!e open("filethatdoesntexist.txt")

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     open("filethatdoesntexist.txt")
004 | FileNotFoundError: [Errno 2] No such file or directory: 'filethatdoesntexist.txt'
bright heron
quick brook
bright heron
#

there is a file named like this

#

this is why idk how i need to fix it

quick brook
bright heron
glad cradle
#

UwU path issues

#

check where you are running the command

bright heron
#

wdym

vale wing
glad cradle
#

unfortunately i gotta go, pls check in what path you are executing the command

#

or is it a script that's opening the file?

slate swan
glad cradle
vale wing
#

From where

glad cradle
#

also pls I'm crying so much on 198

slate swan
#

shouldnt have choosen it

bright heron
#

its saying "the system could find the path"

slate swan
#

you need to be in the directory the file is in before running the command or whatever you run

glad cradle
bright heron
#

there is no directory file

slate swan
bright heron
#

file named like you before?

slate swan
#

may you share the github you downloaded it from?

#

🤦

bright heron
#

?

slate swan
#

blud aint even hiding it

#

Not even trying

#

do i really have to explain that we wont help with such problems

#

too much honesty

bright heron
#

hiding what ????

slate swan
#

!rule 5

unkempt canyonBOT
#

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

bright heron
#

lol

#

xD

slate swan
#

oH I DidN't kNoW

#

funny isnt it

bright heron
slate swan
#

you didnt read terms of service of discord you are using just now?

#

It's called common sense

#

thats unfortunate

bright heron
#

im joining every day a discord server i cant read the rules everytime

#

not really everyday but smth like that

slate swan
#

Those are not even server specific

vale wing
slate swan
#

Which applies any time any server, doesn't matter

slate swan
#

And you won't end up getting banned from just a server, but from Discord overall

#

Anyways, enough off-topic

bright heron
#

ye i need help with luna thing

slate swan
#

No you won't get any help

bright heron
#

why

slate swan
#

For the reason above

bright heron
#

bruh

slate swan
#

xd

vale wing
#

Moment

slate swan
#

dont continue asking questions about this problem here anymore thanks :)

bright heron
#

kk

#

cya byebye

vale wing
slate swan
#

blud left

vale wing
#

Off to dpy server

slate swan
#

Will get slammed there

vale wing
#

😔

shrewd apex
#

what happened 👀

#

did i miss some interesting stuff

slate swan
shrewd apex
#

ayo

#

473 stars

#

damnnnn

slate swan
#

are you one of them 🧐

shrewd apex
#

nope

#

didn't even know something like this exists loooli

slate swan
#

but the star graph site is cool to know

shrewd apex
#

mhm

slate swan
#

10 stars brbrbrbr_animated

quick brook
#

currently have 19 on my primary bot

severe locust
quick brook
glad cradle
#

Save me from #198

vale wing
#

But didn't find you

glad cradle
#

how did you not find me, i was there working on #198 (I'm here since 3 weeks pls send help actually bobux is an enslaving organization pls)

vale wing
#

Ok

#

Donate 10 mil to charity

slate swan
#

right after

pastel shale
#

hey, does anyone have a working script for a basic discord bot? I've tried everything, I've looked everywhere but nothing works for me. Does anyone have any suggestions?

glad cradle
glad cradle
# pastel shale hey, does anyone have a working script for a basic discord bot? I've tried every...

mh @slate swan made a quite popular template, you just need to set some things https://github.com/kkrypt0nn/Python-Discord-Bot-Template

GitHub

🐍 A simple template to start to code your own and personalized Discord bot in the Python programming language. - GitHub - kkrypt0nn/Python-Discord-Bot-Template: 🐍 A simple template to start to code...

slate swan
slate swan
quick brook
#

just use umbra's sync command or jsk's sync command

#

also store the aiohttp.ClientSession() as an attr on your subclassed bot

#

alos refrain from spamming aiosqlite conns

slate swan
#

Same for db connection

quick brook
#

i see

slate swan
#

I just can't be arsed to code in python anymore KEK

quick brook
#

fair enough

#

i might work on my own template for bots

mighty pilot
#

Is there something wrong with this?

Main file

import discord
from discord.ext import commands

TOKEN =

bot = commands.Bot(command_prefix="^", intents=discord.Intents.all())

    
@bot.event
async def setup_hook():
    await bot.load_extension("cogs.my_cog1")
    print('ready')
    
@bot.tree.command()
async def test(interaction:discord.Interaction):
    await bot.tree.sync()
    await interaction.response.send_message(content = 'testing')

bot.run(TOKEN, reconnect = True)```


Cog file
```py
import discord
from discord.ext import commands

class MyCog1(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @commands.command()
    async def testing(self, interaction:discord.Interaction):
        await interaction.response.send_message(content= 'Testing2')

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

It runs, if I put a print before the cog class it'll print but the command won't load

#

No errors

dire mason
#

How do you get the roles, and joindate of the author.

hushed galleon
mighty pilot
#

Oooo that's where it is

#

Need app_commands

#

Thanks. Been a long day pixelchu

hushed galleon
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role) that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
hushed galleon
#

lol the docs messed up the markdown on that

dire mason
hushed galleon
#

loop through each role object and use its .mention property to get the mention as a string

#

!d discord.Role.mention

unkempt canyonBOT
hushed galleon
#

also consider using the allowed_mentions= parameter to avoid pinging those roles, if you haven't already

faint dragon
#

has anyone here gone deep into doing custom logic on d.py?

#

ex; entirely custom cog/command logic (loading, prepping, doing all the command's checks, invoking)

wanton current
#

Why

quick brook
#

just why

golden portal
#

custom cog require using metaclass and custom command logic require subclassing command itself which can get pretty annoying

runic wraith
#

how can I fetch the vc where the user is who interacted with the button?