#discord-bots

1 messages Β· Page 197 of 1

viral stump
#

so yeah, no big deal

hushed galleon
#

having a user-local installation is generally more convenient since you wont need to deal with privilege escalation, e.g. when installing packages

viral stump
hushed galleon
#

in the context of someone installing python to write their own programs, thats the case

viral stump
#

anyway, is everything working now?

coral glen
#

mmmm lets see

#

so what do i run first

viral stump
#

admin cmd -> pip install discord.py

coral glen
viral stump
#

._.

#

how?

pliant gulch
#

Access through python

viral stump
#

type "python" in terminal and show screenshot

coral glen
viral stump
#

I don't get it the version is good

#

oh wait

coral glen
#

πŸ˜”

viral stump
#

I think I got what's going on, you have installed python for local user in the first place then installed it for everyone

#

but the default launch is probably set for the local user wich don't have the pypi config

#

go to control pannel then uninstall everything python related and do a clean install

coral glen
#

??

viral stump
#

there should be python launcher and your version

#

letme show you

#

theses 2

#

uninstall them

coral glen
#

thats what i did every time

viral stump
#

oof

coral glen
#

uninstalled the launcher too

viral stump
#

this is weird

autumn junco
#

AttributeError: 'InteractionResponse' object has no attribute 'followup'

autumn junco
#

shit

#
Traceback (most recent call last):
  File "C:\Users\Xmich\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\Xmich\OneDrive\Desktop\New folder\Website\main.py", line 66, in select_callback
    await interaction.followup(view=view)
TypeError: 'Webhook' object is not callable
naive briar
#

!d discord.Webhook.send - followup returns a webhook, read the docs

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

Sends a message using the webhook.

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

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

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

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
autumn junco
#

interaction.response.send_message("Do this", view=view, ephemeral=True)

slate swan
viral stump
#

it does work

slate swan
#

the way you have it worded will not work

#

hence why it says the word β€œpip” is not recognized as a command

viral stump
slate swan
#

i’ve had pip to path and even if i did try it the way you worded it, it wouldn’t work

naive briar
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.
slate swan
#

again hence why it is unrecognized as a command

viral stump
#

maybe it's a bad config in your end, probably antivirus or just weird path settings

#

parental control maybe? πŸ‘€

#

or non admin user

slate swan
#

…

ionic garden
#

how do i take a list of users in an app command

slate iris
#

whats the best discord bot library to use?

#

I want one that has slash commands and forms

ionic garden
autumn junco
#

How do I create a channel under a specific category

naive briar
#

Or modal

ionic garden
#

could i have an example?

naive briar
#

Slash commands are not good at this in general

autumn junco
#

@ionic garden maybe you could make it take in a string then you take in the user id and split it for each space?

ionic garden
#

yeah but ngl that seems kinda scuffed

autumn junco
autumn junco
vale wing
vale wing
ionic garden
#

could i have an example for possibly how to do that?

vale wing
#

!d discord.ui.UserSelect

unkempt canyonBOT
#

class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current members of the guild.

If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

New in version 2.1.
slate iris
#

idk what u mean by modals impl sucks sorry im new to this type of thing

vale wing
slate iris
#

alr

#

Disnake does look a bit easier when looking at the code

vale wing
#

Except you might not be able to do manual sync but who needs it after all

slate iris
#

alr

#

ty

vale wing
autumn junco
#

How do I create a channel under a specific category

slate swan
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.

The `overwrites` parameter can be used to create a β€˜secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
slate swan
#

category kwarg

ionic garden
#

in a view, can i show diff buttons to diff users?

ionic garden
#

that's an f

vale wing
ionic garden
#

i have a mysql db

#

should i store discord uids as bigints or strings, or is it a matter of preference

glad cradle
#

I would store them as bigints

#

but basically strings or bigints does not change much

pallid meadow
#

Technically it’s more optimized to use bigints

#

But I highly doubt that would be an issue for you

glad cradle
#

bigint should take less memory

vale wing
#

String typically takes more yeah

#

Bigint should take 64 bits which means 8 bytes, string takes a byte per character in UTF-8 iirc

glad cradle
#

yeah

vale wing
#

So it's obviously better to use bigint

#

Strings are gonna take more than twice more

slate swan
#

!d discord.ui.button

#

!d discord.Interaction

slate iris
#

Anyone know how to make a slash command guild only in disnake?

viral stump
#

Disnake?

alpine cove
#

disnake kinda weird ngl

shrewd apex
shrewd fjord
#

!d disnake.ext.commands.guild_only

unkempt canyonBOT
#

@disnake.ext.commands.guild_only()```
A [`check()`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.check "disnake.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.NoPrivateMessage "disnake.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://docs.disnake.dev/en/latest/ext/commands/api.html#disnake.ext.commands.CheckFailure "disnake.ext.commands.CheckFailure").
shrewd fjord
#

It's for normal prefix cmd, try finding slsh cmds deco too

#

Tho as far as i know the decos are same with commands and slash command in disnake

vale wing
alpine cove
vale wing
#

I know both libs and still I prefer disnake

#

I have stated its pros and cons somewhere

#

My question was about your opinion to it

alpine cove
#

I dont know disnake in general but some other forkd like pycord

#

most of them still uee the old app cmd syntx

#

their code is inefficient

#

...

vale wing
#

You mean one where all parameters had to be described in decorator?

alpine cove
#

yes you prb wouldnt call it syntax would you?

glad cradle
#

Imagine not having different types of interactions

alpine cove
glad cradle
#

they were introduced to simplify things and to achieve a better design but ig you don't understand them at all 😦

alpine cove
cloud dawn
#

Monin' ducky_dave

alpine cove
cloud dawn
#

It's quite here πŸ‘€

slate swan
#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
pulsar helm
#

hey guys

#

how can i create a discord bot with python lang ?

swift pumice
#

guys

#

is it possible to make a event that does something when a member RECEIVES a role?

#

like i mean the member is for like 1 hour on the server now and when i give him a role something runs?

vocal snow
#

on_member_update i suppose

swift pumice
#

ok, thanks

swift pumice
marsh crypt
#

Can discord bot Hey how it going is it possible to take data from google sheets and paste then click ok?

alpine cove
cloud dawn
wraith meteor
#

Hi some one have an example to send msg from python code to nextcord chatbot?

distant burrow
#

Hey, I'm trying to create a slash command using py-cord 2.4.0
If I follow the documentation's provided code:

import discord

bot = discord.Bot()

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

@bot.slash_command(guild_ids=[your, guild_ids, here])
async def hello(ctx):
    await ctx.respond("Hello!")

bot.run("your token here")

I get this error:

module 'discord' has no attribute 'Bot'
  File "D:\Projects\LeagueNebula_Bot\utils.py", line 18, in <module>
    bot     = discord.Bot()
  File "D:\Projects\LeagueNebula_Bot\main.py", line 1, in <module>
    from utils import *
AttributeError: module 'discord' has no attribute 'Bot'```
#

Can someone explain why, and how I can solve this?

#

Just for clarification, the bot is multifile. definitions n stuff are in utils, but they're imported into main. So that shouldn't be the problem

slate swan
distant burrow
#

yes, i have already done that

thin raft
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

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

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

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

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

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

New in version 2.0.
slate swan
thin raft
#

oh mb then

#

._.

#

the docs doesn't say the same

#

@slate swan

slate swan
thin raft
#

why doesn't he try to use commands.Bot

#

and see if it works

distant burrow
#

because I already did πŸ’€

#

I can try again ig

thin raft
#

which is the name of yor file?

distant burrow
#

definition and import is in utils.py
command i'm trying to run and bot setup are in main.py

#

utils is imported in main

thin raft
#

send full code

distant burrow
#

if I use commands.Bot I must use command_prefix which is what im trying to avoid

thin raft
#

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

thin raft
#

which ide / code editor are you using?

distant burrow
#

vscode

#

utils.py

#importing libraries
import discord
from discord.ext import commands

import os

import sqlite3

GUILDS = [  "1075018380064596021",  #Bot Playground
            "1073753136558256179",  #League Nebula
            ]

bot = commands.Bot()

con = sqlite3.connect("LeagueNebula.db")
cur = con.cursor()
thin raft
#

ctrl + left click on import discord

distant burrow
#

main.py

from utils import *

@bot.event
async def on_ready():
    print("Bot is online.")
    await bot.change_presence(status=discord.Status.online, activity=discord.Game("Hi there!"))

#cogs here

#####################################################
#                   TEST COMMAND                    #
#####################################################

@bot.slash_command(description="first slash command", guild_ids=GUILDS)
async def test(ctx):
    await ctx.send("Succes!")

bot.run(os.environ.get("TOKEN"))
thin raft
#

I am just confused on your organisation

distant burrow
#

why

#

makes sense to me

#

utils should be available everywhere

#

main is the file that starts the bot

thin raft
#

send THE WHOLE file

distant burrow
#

it's a folder!

thin raft
#

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

distant burrow
#

I sent you everything already

thin raft
#

try to use everything in the same file and see what it happes

distant burrow
#

the same issue persists

#

which I don't find very surprising as nothing really changes

thin raft
#

ctrl + right click on import discord

#

where does it get you?

distant burrow
#

right click does nothing

#

left click sends me to init.py

thin raft
distant burrow
#

ik

thin raft
#

try left click then

distant burrow
#

yeye

thin raft
#

send ss of the whole screen

#

screenshot

distant burrow
#

it does indeed not contain discord.Bot

#

it does have Client, but that isn't compatible with "slash_command"

#

here's the whole init file

#

Im not sure about the folder its in. I will have a look when I get home.
It could be discord.py hasn't uninstalled fully

distant burrow
#

I force deleted it

#

Installed pycord again

#

And now import discord cant be resolved

static holly
#

With easy-pil πŸ™‚

quick gust
#

or are u just sharing the code

static holly
#

just sharing πŸ™‚

vocal snow
#

pretty

static holly
gilded cedar
#

i try to make hybrid meme command but for some reason its spamming for no specific reason

#

@client.hybrid_command()
async def memes(ctx):
reddit = praw.Reddit(
client_id = "id",
client_secret = "your-secret",
user_agent = "put-any-name",
check_for_async=False
)
subreddit = reddit.subreddit("memes")
all_subs = []
hot = subreddit.hot(limit=50)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
url = random_sub.url
em = discord.Embed(color=0xb8f3ff)
em.add_field(name="Have Some Memes", value="From r/memes", inline=False)
em.set_image(url = url)
await ctx.send(embed = em)

vocal snow
#

spamming what?

gilded cedar
#

keep spamming random images

vocal snow
#

well you're fetching 50 submissions and sending all of them in your code

#
    hot = subreddit.hot(limit=50)
    for submission in hot:
#

not sure why you have that if you only want to send it once

gilded cedar
#

it sent one image once before switching to hybrid commands

#

now it sends same image

gentle nova
#

TypeError: type 'Collection' is not subscriptable , basically its not reading from modules

#
from modules import bank_funcs, inventory_funcs
from config import Auth

modules name white , but everything is , modules folder and files in there but why not readig

ionic garden
vale wing
#

!d discord.ui.UserSelect

unkempt canyonBOT
#

class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None)```
Represents a UI select menu with a list of predefined options with the current members of the guild.

If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

New in version 2.1.
vale wing
#

Yeah max_values

ionic garden
#

how do i do that

#
class UserInvite(discord.ui.View):
    @discord.ui.select(cls=UserSelect, placeholder="Select a user please!")
    async def my_user_select(self, i: discord.Interaction, select: UserSelect):
        await i.response.defer()
```bc this is how i'm using it rn & i don't see a place to pass it in
vale wing
#

Ah you are using a deco

#

!d discord.ui.select

unkempt canyonBOT
#

@discord.ui.select(*, cls=<class 'discord.ui.select.Select'>, options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.

To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
vale wing
#

There's max_values kwarg too

ionic garden
#

ah there we go

#

any way to perform a check on the selected users?

gentle nova
#

anyone can help me tho

young dagger
#

Is there any easier way to fix this?

        invite_message = None

        try:
            invite_message = await next_player.send(embed=invite_embed)
        except discord.Forbidden:
            pass

        await asyncio.sleep(60)

        if invite_message is not None:
            await invite_message.delete()```
#

I'm getting Local variable 'invite_message' might be referenced before assignment without invite_message = None

chilly dove
#

if .send throws discord.Forbidden then invite_message will not be a variable

gentle nova
#

File "c:\eco\modules\bank_funcs.py", line 46, in DataBase
def cursor(self, table_name: str) -> Collection[Mapping[str, Any]]:
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
TypeError: type 'Collection' is not subscriptable

ionic garden
gentle nova
#

@ionic gardenBut that error linking to this

#
def cursor(self, table_name: str) -> Collection[Mapping[str, Any]]:
        return self.db[table_name]
ionic garden
#

where did you import Collection

gentle nova
#

mongo

ionic garden
#

just send your whole code

gentle nova
#

!paste

ionic garden
#

hm, don't have much experience w/ pymongo
but maybe it just isn't one of those subscriptable types like typing.List

gentle nova
#

how's that

vocal snow
#

at the very start of the module

gentle nova
#

same

vocal snow
#

-> "Collection[Mapping[str, Any]]"

gentle nova
#

dont understand at this moment :d

#

lack of brains atm

#

@vocal snowcan you explain more

static holly
#

please how to get the member avatar in on_member_join?

vocal snow
static holly
#

member.avatar.url not work

vocal snow
static holly
gentle nova
#

@vocal snownot sure

vocal snow
static holly
#

no...

vocal snow
static holly
#

dont work

vocal snow
gentle nova
#

@vocal snowstill learning about everyting

vocal snow
#

are you getting an error or what

vocal snow
#

you should know this stuff first

#

anyways if you don't know about strings im not sure why you are typehinting your code... i guess you copied it from somewhere

static holly
vocal snow
static holly
#
@commands.Cog.listener()
    async def on_member_join(self, member):
        channel= self.bot.get_channel (1074708154799116348)
        userData = {
           "name": f"{member.name}",
           }
        background = Editor(Canvas((900, 300), color="#242424"))
        profile_picture = await load_image_async(member.display_avatar)
        profile = Editor(profile_picture).resize((150, 150)).rounded_corners(radius=20)
vocal snow
#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
vocal snow
#

and then you can use .url on that

static holly
#

if i use member.avatar.url it dont work, i have a traceback with this

vocal snow
#

.avatar and .display_avatar are different things

sick birch
#

No

#

Ahhhh glitch

#

Was trying to reply to the Lancebot message the same time it deleted, lol

vocal snow
#

lancebot needs to change prefix πŸ˜”

static holly
#
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\welcome.py", line 21, in on_member_join
    profile_picture = await load_image_async(member.avatar.url)
AttributeError: 'NoneType' object has no attribute 'url'
#

@vocal snow

vocal snow
#

they didn't set a custom avatar

static holly
#

its a test profile...

vocal snow
static holly
#

or can i pass this step?

vocal snow
#

skip it

#

use .display_avatar directly

vocal snow
gentle nova
#

@vocal snowCan you explain me how to use string in this situation ?

vocal snow
#

put quotes around the type

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

static holly
# vocal snow skip it
@commands.Cog.listener()
    async def on_member_join(self, member):
        if member.avatar.url == None:
            pass
        channel= self.bot.get_channel (1074708154799116348)
        userData = {
           "name": f"{member.name}",
           }
        background = Editor(Canvas((900, 300), color="#242424"))
        profile_picture = await load_image_async(member.avatar.url)
slate swan
gentle nova
#

i did it , but same problem

vocal snow
vocal snow
slate swan
#

for some reason the function is not callled by compiler

#

depiste being called in theory

gentle nova
#

but im getting error and for this class DataBase:

vocal snow
gentle nova
#

oh right, got it working now

static holly
# vocal snow that's unnecessary... just use member.display_avatar directly
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event     
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\welcome.py", line 21, in on_member_join
    profile_picture = await load_image_async(member.display_avatar)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\easy_pil\utils.py", line 56, in load_image_async
    async with session.get(link) as response:
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 1138, in __aenter__    
    self._resp = await self._coro
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 422, in _request       
    url = self._build_url(str_or_url)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 356, in _build_url     
    url = URL(str_or_url)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\yarl\_url.py", line 154, in __new__
    raise TypeError("Constructor parameter should be str")
TypeError: Constructor parameter should be str
vocal snow
#

since your function expects a string, not an Asset

slate swan
#

or better

vocal snow
#

you need to have a self parameter

slate swan
#

i typed the selt thing][

#

but still not working

vocal snow
#

where?

#

and a lot of your code is broken

#

you're using .append with more than 1 argument in many places

slate swan
#

in roll_result

slate swan
#

being one part the roll result

#

and the other the total, at least on sub_roll

gentle nova
#

@vocal snowIf i want to edit shop, to buy not items but Roles, how supposed i do it ?

#

Ill do myself, and send it here if its right πŸ˜„

#

But wait, i need edit whole DB , its bad

static holly
#

Thanks

quick gust
#

if I have a datetime.datetime object, how would I utilize it to display a unix timestamp?

slate swan
dim cosmos
quick gust
dim cosmos
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
vocal snow
#

there's also this for a bit of convenience

quick gust
#

alright thanks!

slate swan
#

i don't know what i need to fix

#

so Zeffo, why my roll is not working?

#

maybe you could help me on fixing on what is broken on my code

dim cosmos
#

@slate swan what's this supposed to do
indice.append([cont,cont+1], indz)

slate swan
dim cosmos
#

you're trying to append 2 arguments at once

#

.append() takes 1

slate swan
#

like meta data?

dim cosmos
#

i'm talking about the appending part

#

it should be like

#

indices.append('something')

slate swan
#

that's what i'm talking about

dim cosmos
#

what you're doing is indices.append('something', 'something2')

slate swan
#

i was planning to store two arguments at once

#

yes

dim cosmos
#

yea

dim cosmos
slate swan
#

oh i see

#

and if i try [[cont, cont+1], indz]?

#

will it count as metadata?

dim cosmos
slate swan
#

nice

#

i fixed stuffs

#

why my sub_roll function is not working?

dim cosmos
slate swan
# dim cosmos what's the error

it doesn't show, it just stop working and gives me the else output that the args are invalid. It didn't even enters the function

#

is there a debug code that allows me to show error message?

#

so i can show you something for you to help me?

dim cosmos
#

do u have jishaku installed

swift yacht
#

Can someone help me? I'm trying to create a bot that looks for empty groups on a web page, but when I try it, the bot does nothing and gives me an error.

swift yacht
# dim cosmos what's the error

in group_scanner
^^^^^^^^^^^^^^^^
proxy_auth, proxy_addr = next(proxy_iter)
proxy_auth, proxy_addr = next(proxy_iter)
File "C:\Users\Angel\OneDrive\Escritorio\h0nderobloxclaimablegroupfinder-main\core\threads\group_scanner.py", line 24, in group_scanner
proxy_auth, proxy_addr = next(proxy_iter)
proxy_auth, proxy_addr = next(proxy_iter)
StopIteration
StopIteration
^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^
proxy_auth, proxy_addr = next(proxy_iter)
StopIteration
StopIteration
^^^^^^^^^^^^^^^^
StopIteration

#

and it repeats like 20 times

dim cosmos
swift yacht
slate swan
#

jishaku

swift yacht
dim cosmos
#

& load it as a cog

slate swan
#

where do i type?

dim cosmos
#

in ur setup hook

slate swan
#

so, it's windows CMD or... ?

dim cosmos
#

pip install jishaku in ur terminal or cmd

#

and load it as a cog in ur setup hook

swift yacht
slate swan
#

error:

swift yacht
#

someone help me

dim cosmos
slate swan
#

yes

dim cosmos
#

try pip3

#

pip3 install jishaku

swift yacht
dim cosmos
slate swan
#

same thing:

swift yacht
dim cosmos
slate swan
#

no

dim cosmos
#

to figure out what the error is

swift yacht
dim cosmos
dim cosmos
swift yacht
slate swan
#

list indices must be integers or slices, not str

#

guess i understood what it meant

#

guess i need to put .lenght

#

so it would be interger

#

to get the variables from the list

shrewd apex
slate swan
#

what would happens if i use enumerate?

dim cosmos
#

i'm traumatized for life

slate swan
#

oh, i got a better idea

#

i could just use x instead of the thing

shrewd apex
chilly dove
shrewd apex
unkempt canyonBOT
#

Ever find yourself in need of the current iteration number of your for loop? You should use enumerate! Using enumerate, you can turn code that looks like this:

index = 0
for item in my_list:
    print(f"{index}: {item}")
    index += 1

into beautiful, pythonic code:

for index, item in enumerate(my_list):
    print(f"{index}: {item}")

For more information, check out the official docs, or PEP 279.

slate swan
#

or i could jsut use x

#

that's what i figured out

#

i made a dumb misstake

shrewd apex
shrewd apex
#

dpy will handle it in backend

#

and just pass on the forbidden

#

or even better use interactions and send an ephemeral message that way u wont have to waste an api call on deleting

slate swan
#

okay now i received this:
1d6
Roll.sub_roll() takes 1 positional argument but 2 were given

#

it was just only 1 argument

shrewd apex
#

send code lol

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
#

here @shrewd apex

distant burrow
#

I'm running into an issue trying to use cogs with discord.Client, does anyone have some time?

shrewd apex
#

self, whatever

shrewd apex
chilly dove
distant burrow
#

I want to use slash commands, but I also want to organize my code

shrewd apex
#

skill issue

distant burrow
#

true

#

im just gonna start coding my discord bot in c++ amirite

shrewd apex
#

sure

distant burrow
#

awesome idea

#

dies of dying

slate swan
shrewd apex
#

sub_roll function bro

slate swan
dim cosmos
shrewd apex
slate swan
#

i don't know which line. What are the aliases?

dim cosmos
#

oh my god

shrewd apex
#

its ur own code πŸ’€

distant burrow
chilly dove
# slate swan i didn't got you

you are passing a default list as a function argument named aliases if you expect that to work for aliases it wont you need to put that into the .command() decorator

dim cosmos
shrewd apex
#

line 151

distant burrow
#

bruh why the fuck did I not learn about this earlier

#

i've been trying to fix this for hours

dim cosmos
#

all you have to do is
@commands.hybrid_command()
instead of
@commands.command()

shrewd apex
dim cosmos
#

problem solved

distant burrow
shrewd apex
distant burrow
#

@dim cosmos thanks for the tip

slate swan
#

fixed:

shrewd apex
#

good

dim cosmos
slate swan
#

put self into the function... uhmm

#

i need an example

shrewd apex
#

😡

dim cosmos
shrewd apex
#

literally me

dim cosmos
#

you're gonna make us cry holy shit

shrewd apex
slate swan
shrewd apex
slate swan
#

like this?

dim cosmos
#

yes

shrewd apex
#

yay

dim cosmos
#

also you should stop using
something = []

#

just do something = list()

#

it's faster

shrewd apex
#

copilot i am guessing from those comments

civic fractal
#

something = [] is correct

slate swan
dim cosmos
shrewd apex
#

the function call takes longer

dim cosmos
#

Ok

#

mb

civic fractal
#

something = [] is over twice as fast

#

and it's way more readable

dim cosmos
#

thanks

civic fractal
#

np

shrewd apex
#

!timeit

set()
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 timeit job has completed with return code 0.

2000000 loops, best of 5: 104 nsec per loop
shrewd apex
#

!timeit

{*()}
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your 3.11 timeit job has completed with return code 0.

2000000 loops, best of 5: 145 nsec per loop
shrewd apex
#

hmm

dim cosmos
#

!timeit

async with aiohttp.ClientSession() as session:
  async with session.get("https://ws.audioscrobbler.com/2.0?method=track.getInfo&username=tbpn&api_key=e739760b740efae08aeef62f0e15d7b7&artist=tyfontaine&track=dummy&format=json&autocorrect=1") as response:
    result = await response.json()
result['track']['name]
unkempt canyonBOT
#

@dim cosmos :x: Your 3.11 timeit job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<frozen runpy>", line 198, in _run_module_as_main
003 |   File "<frozen runpy>", line 88, in _run_code
004 |   File "/usr/local/lib/python3.11/timeit.py", line 376, in <module>
005 |     sys.exit(main())
006 |              ^^^^^^
007 |   File "/usr/local/lib/python3.11/timeit.py", line 315, in main
008 |     t = Timer(stmt, setup, timer)
009 |         ^^^^^^^^^^^^^^^^^^^^^^^^^
010 |   File "/usr/local/lib/python3.11/timeit.py", line 123, in __init__
011 |     compile(stmtprefix + stmt, dummy_src_name, "exec")
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/tiyimufiho.txt?noredirect

slate swan
#

i never knew that split converts numbers into interger when there is no character. Good to know

slate swan
#

i got this:
int() argument must be a string, a bytes-like object or a real number, not 'list'

young dagger
slate swan
#

when entered the sub_roll

civic fractal
#

just a single list of strings

#

and int(["1", "2", "3"]) doesn't work because that isn't a single cohesive integer

slate swan
#

oh gotcha

shrewd apex
slate swan
#

it seems that i need to turns into INt each

shrewd apex
#

depending on your situation

civic fractal
#

you could do py string_parts = strings.split() integers = [int(string_part) for string_part in string_parts]

slate swan
#

is there a command that converts all stuffs in a list?

shrewd apex
#

map

civic fractal
#

i.e. [int(stuffs) for stuffs in a_list]

#

to convert each stuffs in a list to an integer

slate swan
#

guess i'm gonna make a research

#

guess this works:
for i in range(0, len(test_list)):
test_list[i] = int(test_list[i])

#

unsupported operand type(s) for +: 'int' and 'list'

slate swan
austere vale
#
  #work command
  @nextcord.slash_command(description='Grind for da money')
  @cooldowns.cooldown(1, 1800, bucket=cooldowns.SlashBucket.author)
  async def work(self, interaction):
    chances=random.randint(1,4)
    if chances==1:
      return await interaction.send('You got nothing. F')
    amount=random.randint(1,10)
    res=await self.update_wallet(interaction.user,amount)
    if res==0:
      return await interaction.send('No account has been found, so one has been created for you. Please run the command again after the cooldown!')
    await interaction.send(f'You got {amount} coins!')

0|bot  | Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7fce4350f970>:
0|bot  | Traceback (most recent call last):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/nextcord/application_command.py", line 906, in invoke_callback_with_hooks
0|bot  |     await self(interaction, *args, **kwargs)
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/cooldowns/cooldown.py", line 103, in inner
0|bot  |     async with _cooldown(*args, **kwargs):
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/cooldowns/cooldown.py", line 248, in __aenter__
0|bot  |     async with bucket:
0|bot  |   File "/usr/local/lib/python3.8/dist-packages/cooldowns/cooldown_times_per.py", line 50, in __aenter__
0|bot  |     raise CallableOnCooldown(
0|bot  | cooldowns.exceptions.CallableOnCooldown: This function is being rate-limited. Please try again in 1794 seconds.
0|bot  | The above exception was the direct cause of the following exception:
0|bot  | nextcord.errors.ApplicationInvokeError: Command raised an exception: CallableOnCooldown: This function is being rate-limited. Please try again in 1794 seconds.

how can i modify my command to send a message like "You are on cooldown for this command. Please wait x more seconds?"

slate swan
#

Sucess: Bot is connected to discord!
Ping.py is ready
Roll.py is ready
started rolling...
indz: 1
indz: d
indz: 6
['1d6']
testing # occurence
sucess on habilited
initiating rollling
sub rolling...
1d6
rolling...
[1, '6']
unsupported operand type(s) for +: 'int' and 'list'

shrewd apex
#

learn basics of python first smh

austere vale
#
try:
  #work command
except Exception:
  interaction.send(Exception)

i tried this but it didnt work (i get the same error), im not sure what else to do

vale wing
#

It's on_application_command_error

#

!d nextcord.ext.application_checks.on_application_command_error

unkempt canyonBOT
austere vale
#

ahhh ok i'll try to put that in my Help cog then

vale wing
#

Why the hell is it located in checks

austere vale
#

thank you!

spiral crypt
#

hey how would I get this embed to send a link to the channel instead of just the raw text?

    if welcome_channel:
        embed = discord.Embed(title=f"Welcome {member.name}!",
                              description=f"Thank you for joining our server! Please take a moment to read the "
                                          f"#{discord.utils.get(member.guild.channels, name='rules')} and introduce yourself in the "
                                          f"#{discord.utils.get(member.guild.channels, name='introductions')} channel.",
                              color=0x00ff00)
        embed.set_thumbnail(url=member.avatar_url)
        await welcome_channel.send(embed=embed)
spiral crypt
#

It comes out like that but I want it to say #introductions and #rules with a "link" to the channel

#

just the rules link popped up in that message ^

dim cosmos
#

you could just get the channel & mention it

spiral crypt
#

how would i go about doing that?

#

cuz i get the channel in the code block above

dim cosmos
#
if welcome_channel:
        embed = discord.Embed(title=f"Welcome {member.name}!",
                              description=f"Thank you for joining our server! Please take a moment to read the "
                                          f"{discord.utils.get(member.guild.channels, name='rules').mention} and introduce yourself in the "
                                          f"{discord.utils.get(member.guild.channels, name='introductions').mention} channel.",
                              color=0x00ff00)
        embed.set_thumbnail(url=member.avatar_url)
        await welcome_channel.send(embed=embed)β€Š
spiral crypt
#

oooh

dim cosmos
#

discord.utils.get(bla bla).mention

#

or you could also do guild.get_channel(channel).mention

spiral crypt
#

gotcha thankies :3

dim cosmos
#

πŸ‘

slate swan
proud apex
#

Is it possible to do a global check for slash commands, if the user id is not in the database, then an error will be displayed?

dim cosmos
#

it's possible yea

proud apex
#

how?

dim cosmos
#

which db are u using

proud apex
#

postgre

dim cosmos
#

if it is do everything normally

#

if it isn't send an error

proud apex
#

I know it. and how to make the most global slash check?

dim cosmos
slate swan
#

okay, i detected that for some reason x is detected as an array, not as a value that should be:

            print(x)
            if x == "+":
                total = total+1
            elif x == "-":
                total = total-1
            else:
                total = total+x
        print(total)
sub rolling...
1d6
rolling...
[1, '6']
entered while
[2]
[[2]]
[2]
unsupported operand type(s) for +: 'int' and 'list'

Why sometimes python don't detect it as a just value? That's strange

#

maybe i need to cast?

#

okay, i discovered the problem, x is being treated as a list not as a value. What is strange

#

okay i discovered why

#

when i used append it was creating a list in a list

#

since the list was already created by my algorith

#

that's why it wasn't working

slate swan
#

i got this error and code is for sending messages to multiple webhooks

#
import requests
import os.path
import os
import time

def hook():
    try:
        if os.path.exists('./hooks.txt') == True:
            if os.stat("hooks.txt").st_size == 0:
                print("\nNo hooks found. Please add Webhook URLs to the hooks.txt file.")
            else:
                content = input('Enter what the webhook(s) should send: ')
                while True:
                    for line in open('hooks.txt'):
                        line = line.strip()
                        req = requests.post(
                            line,
                            json = {
                                "content": content
                            }
                        )
                        statusCode = str(req.status_code) # Thank you Python for not allowing me to use req.status_code directly
                        if statusCode.startswith('2') == True:
                            print('[' + str(req.status_code) + ']' + ' Message successfully sent.')
                        elif statusCode.startswith('4') == True:
                            if statusCode == '429':
                                retry = int(req.headers['retry-after']) / int(1000)
                                print('\nGetting ratelimited. Retrying in ' + str(retry) + ' seconds.\n')
                                time.sleep(retry)
                            else:
                                print('[' + str(req.status_code) + ']' + ' Message not sent.')
        elif os.path.exists('./hooks.txt') == False:
            print('\nNo hooks.txt file found. Please create a hooks.txt file and add webhook URLs to it.')
    except KeyboardInterrupt:
        print('\nExiting...')
        exit()

hook()
young dagger
#

!e

timestamp = datetime.datetime.now() + datetime.timedelta(seconds=60)
fmt_time = discord.utils.format_dt(timestamp, "R")
print(fmt_time)```
unkempt canyonBOT
#

@young dagger :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | NameError: name 'datetime' is not defined
young dagger
#

!e

import datetime
timestamp = datetime.datetime.now() + datetime.timedelta(seconds=60)
fmt_time = discord.utils.format_dt(timestamp, "f")
print(fmt_time)```
unkempt canyonBOT
#

@young dagger :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | NameError: name 'discord' is not defined
naive briar
elfin flint
#

Has anyone tried hosting on an old android phone through termux?

unborn bluff
#

I do that a lot

#

I just sent the code and python3 main.py lol

ionic garden
#

so i have a bunch of views and a bunch of cogs
many views are only used by one cog, but some are used by multiple
should i put all the views in a single package views
or only put those used by multiple cogs in views and the rest in their cogs' file

slate swan
#

i personally put all my views in their own files

#

even if they are being used only once

vital glacier
#

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

vital glacier
#

Code: https://paste.pythondiscord.com/qobotuyehu

Error:

Traceback (most recent call last):
  File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\root\Desktop\project\cogs\Utility.py", line 90, in afk
    timestamp = int(round(datetime.now().timestamp()))
AttributeError: module 'datetime' has no attribute 'now'

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

Traceback (most recent call last):
  File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\root\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'datetime' has no attribute 'now'

anyone?

vital glacier
#

ok ty

vital glacier
smoky sinew
#

what does that mean

vital glacier
#

well

smoky sinew
#

oh

#

i get it, it's an afk system

vital glacier
#

yeah

#

any idea?

smoky sinew
#

why are you connecting to the database multiple times

#

you're only supposed to connect once

vital glacier
#

its once in the listener and then one in the afk command itself

smoky sinew
#

what's the point of that

vital glacier
#

i still need to make it so it connects on when i run the bot lmfao

#

ok so it does send the message on mention, just when i type it doesnt welcome back and remove it from the db

smoky sinew
#
class CustomBot(commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.database = None

    async def setup_hook(self):
        self.database = await aiosqlite.connect("database.db")

    async def close(self):
        await self.database.commit()
        await self.database.close()
        await super().close()
#

use something like this to not connect to it twice

#

then you can just use bot.database

vital glacier
#

oooh

smoky sinew
#

i doubt it will fix your issue but at least that way you won't connect to your database every time a message is sent

vital glacier
#

ok, and that means i can remove the whole aiosqlite.connect(db) on every command/event i use it for?

smoky sinew
#

yes

#

just use ```py
async with self.bot.database.cursor() as cursor:
...

instead
vital glacier
#

ok

#

thank you πŸ‘

smoky sinew
#

have you tried seeing if if data runs?

vital glacier
#

when i made it, it worked. its ever since the datetime thing error it didnt work

#

otherwise i never changed the code

#

i can pull the code out of an older bad bot of mine to double check

#

so just double checking, this would work, right?

from discord.ext import commands
import os
import aiosqlite

class Bot(commands.Bot):
    def __init__(self, *args, prefix=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.prefix = prefix
        self.database = None

    async def setup_hook(self):
        self.database = await aiosqlite.connect("void.db")
        for file in os.listdir("cogs"):
            if file.endswith(".py"):
                name = file[:-3]
                await self.load_extension(f"cogs.{name}")

    async def close(self):
        await self.database.commit()
        await self.database.close()
        await super().close()

    async def on_message(self, msg):
        if (
            not self.is_ready()
            or msg.author.bot
            or msg.guild is None
        ):
            return

        await self.process_commands(msg)

shrewd apex
#

nope no intents

vital glacier
#

what do u mean?

#

my intents are in my main file lol

shrewd apex
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

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

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

vital glacier
#

yeah those are in my main file

shrewd apex
#

ic

vital glacier
shrewd apex
#

then it should yeah

vital glacier
#

on that problem^

shrewd apex
vital glacier
#

none set up rn

shrewd apex
#

set it up and raise an error

vital glacier
#

still working on one when i figure that out properly, i had one but idk what happened to it, i lost the code for it lmfao

shrewd apex
#

we will know what's wrong

#

error handler needed for debugging

vital glacier
#

ok

smoky sinew
#

nvm

vital glacier
#

it does

#

i have a prefix cmd setup aswell, so it just grabs it from the db haha

slate swan
#

prefix=None will do nothing but set bot.prefix=None

coral glen
#

a

#

pip still doesnt work

#

malding

vital glacier
#

sometimes windows and installing packages is odd

coral glen
smoky sinew
smoky sinew
coral glen
smoky sinew
#

what do you think the ... is supposed to be

slate swan
#

in dpy internals?

vital glacier
slate swan
#

oh wait that person is not calling super().init

#

lol

vital glacier
#

so for instance: py -m pip install emoji

#

that would make emoji the package

smoky sinew
#

yeah they are, wdym?

vital glacier
smoky sinew
vital glacier
#

oh then idk

smoky sinew
#

yesterday i think

slate swan
vital glacier
#

what do u mean

smoky sinew
#

yeah they did

vital glacier
#

oh LMAO

slate swan
#

pretend like you never read it

#

i just woke up :p

vital glacier
#

i never read anything if u can help me with my problem LOL

smoky sinew
#

getting ready to go to bed for me

vital glacier
#

its not sending welcome back message and not removing from the db

smoky sinew
vital glacier
#

its almost 5am for me

#

im just chilling on whiskey and good music

smoky sinew
#

why are you doing data[0][3] too? how do you know there is going to be any data at all?

vital glacier
#

thats the timestamp

#

if im correct, let me check

coral glen
smoky sinew
#

and what if there is no data?

coral glen
vital glacier
#

yeah that's timestamp

#

the timestamp is in the database tho, thats the weirdest thing

#

because it send the message if the afk person is mentioned

coral glen
#

oh wait

vital glacier
#

and to update it

#

u need to run that whole line, including C:\

#

just to be sure

smoky sinew
#

what's the point of that

#

it's already running that

vital glacier
#

i always do that just to be sure lmfao

coral glen
smoky sinew
vital glacier
#

there u go

coral glen
vital glacier
#

yeah

coral glen
#

alr alr

vital glacier
#

if that doesnt work, just do py -m pip install discord.py

coral glen
#

omgg it worked

#

tysmm

smoky sinew
#

i thought that didn't work yesterday

coral glen
slate swan
#

@vital glacier can you use a database browser to see if the user_id as actually added to the database or not?

vital glacier
#

it has

#

timestamp, status and user_id are all added to the db.

smoky sinew
#

just use a python debugger or add print statements

vital glacier
slate swan
# vital glacier

what was your create table statement, did you create the user_id field as TEXT/VARCHAR by chance?

vital glacier
#

nah, its an integer

#

status is text and timestamp is integer aswell

vital glacier
#

genuinely im too stupid to know how to do that properly LOL

#

i always mess those up, but yet i can figure out how to make a prefix cmd with db etc

#

10/10 would recommend

smoky sinew
#

what do you mean? just put print everywhere to see how far the code reaches

#

print(1) print(2) etc

slate swan
#

is the cog with that listener loaded? thi

#

i tried using code similar to urs and it works

#
import sqlite3

import discord
from discord.ext import commands

(connection := sqlite3.connect(":memory:")).execute(
    "CREATE TABLE afk (uid INTEGER, reason TEXT) "
)

@(bot := commands.Bot("!", intents=discord.Intents.all())).listen()
async def on_message(msg: discord.Message) -> None:
    cur = connection.execute("SELECT * FROM afk WHERE uid = ?", (msg.author.id,))
    if cur.fetchall():
        await msg.reply("the author was afk")


@bot.command()
async def afk(ctx: commands.Context) -> None:
    connection.execute("INSERT INTO afk VALUES (?, ?)", (ctx.author.id, "idk"))
    await ctx.reply("afk added")
    connection.commit()


bot.run(__import__("os").getenv("DEV_TOKEN"))```
#

im using the sync driver but that shouldnt matter

vale wing
#

Sarth is a real big fan of walrus op

slate swan
#

WH_bhagBKL save me a lot of LOC

vital glacier
#

i double checked the database code aswell, it should work.

vital glacier
coral glen
vital glacier
#

still with the afk problem

coral glen
#

is there something wrong with @client.event ?

smoky sinew
smoky sinew
# coral glen

no it's because you don't have anything after on_ready

vital glacier
coral glen
#

oh okk

smoky sinew
vital glacier
#

genuinely, idk how it can be anything else

slate swan
#

like after getting the data using fetchall() , try printing it

#

and try printing "SELECT * FROM table" to verify your data

vital glacier
#

i did that, and the data is there

#

but ima double check it rq, brb

vital glacier
#

so i assume then that the converters are broken

#

i think remaking the command and event with humanize is best then?

naive briar
#

You took too long to respond

#

Consider to defer the interaction

coral glen
#

PS C:\Users.> python3 bot.py
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.

#

what do i do to fix this

vale wing
#

await interaction.response.defer()

vale wing
coral glen
#

so if i do that will i have to reinstall discord.py?

vale wing
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
vale wing
#

There is no embed kwarg

#

If you are new to python, we do not recommend starting learning from a discord bot, as you need this knowledge:

  • basics (variables, loops, math, basic types)
  • simple data structures (dicts, lists)
  • modules and libraries
  • functional programming
  • object-oriented programming
  • async programming principles
#

Yeah just advising

#

Cause you are going to lose lots of time if you continue like this

#

You first defer, then you send

await interaction.response.defer()
...
await interaction.response.send_message(embed=your_embed)```
vocal snow
#

read the example again

naive briar
smoky sinew
#

response.defer

naive briar
#

!d discord.Interaction.followup

unkempt canyonBOT
vale wing
#

There's also no point in deferring then immediately sending. The thing is you gotta respond to interaction within 3 seconds after you got it, if you are unable to do that, you need to defer first, then respond when needed

vale wing
coral glen
smoky sinew
#

python3 will open the microsoft store version

coral glen
smoky sinew
#

you don't have such file then

coral glen
#

hmm

smoky sinew
#

btw i already saw your username yesterday

coral glen
#

:((

smoky sinew
#

you forgot to censor it in one of your screen shots

coral glen
#

so embarrassing

#

i made it in like grade 2

smoky sinew
#

it's not that bad, plus you can always change it

ionic garden
#

how do i send a modal?
does it have to be intertwined w/ a view?

smoky sinew
unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
coral glen
smoky sinew
#

and no you don't need a view to open it @ionic garden

ionic garden
#

yeah that's part of an InteractionResponse

smoky sinew
#

it can't open by itself

ionic garden
#

wait does it not work with hybrid commands

smoky sinew
ionic garden
#

that's a big f

smoky sinew
#

sorry for replying so much

ionic garden
#

was that directed towards me?

smoky sinew
#

yeah

#

hybrid commands have a lot of limitations, you basically get neither benefits of message commands nor application commands

ionic garden
#

lmao i don't see what there is to be sorry for

ionic garden
smoky sinew
#

probably lol, or just pick one

#

well actually, you can still send a modal without a slash command by using a view or some other type of interaction

slate swan
#

Anyone know of a way to get all ban entries of a guild before/after a specific date?

naive briar
#

!d discord.Guild.bans

unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

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

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
ionic garden
#

ok, so is there a tutorial on how to make a discord modal?

naive briar
#

before and after kwargs

coral glen
#

if the name is 'bot.py' then what other file name could it be

naive briar
sick birch
#

by yours truly

smoky sinew
ionic garden
#

is there a select menu field?

naive briar
#

No

slate swan
smoky sinew
#

pretty sure you can only do text inputs lol

#

kind of weird..

naive briar
#

Oh yeah, lol

smoky sinew
#

even though they could definitely do select menus in modals, and the other way around: text inputs in views

slate swan
#

guess i'll have to make do without for now (unless there's something you can do with the audit log) but thanks anyway

ionic garden
#

i see now why danny ragequit dpy dev

smoky sinew
#

oh nvm

slate swan
naive briar
#

There's action to sort the bans

#

Wait, not again

#

Oooo, they have datetime this time

smoky sinew
naive briar
unkempt canyonBOT
naive briar
slate swan
#

thanks, i'll look into this, my only concern is how well the bot would handle a busy server (for which i also had issues with Guild.bans(...))

slate swan
smoky sinew
#

good choice

naive briar
#

You can keep the iterator and iterate when you need it instead of converting it to a list instantly

slate swan
#

Oh yeah true ty

vale wing
# smoky sinew that's not how you fix it..

This method solves all possible issues immediately, I don't wanna sit here and investigate what he has added to path, what is his executable named, what versions he has, whether it was installed from mc store. This method is the easiest, just fixes everything and there are totally no issues with it

vale wing
slate swan
#

.help

ionic garden
#

a friend told me mysql sucks as a db
is this true

vale wing
#

None of dbs suck as long as they meet your needs and are implemented properly

#

I would say mysql wrapper got weird placeholders and their SQL dialect differs from generic slightly more than others

slate swan
vale wing
vital glacier
#

anyone that got experience with humanizer?

slate swan
#

https://paste.pythondiscord.com/aheroloves

I have this command, I will move the block

with open(output_file, "rb"):
        async with ctx.channel.typing():
            await ctx.send(file=discord.File(output_file))```

but my question is there a way that I can get the link of the image after sending it (discord link) like this one
`https://media.discordapp.net/attachments/1052225384093061175/1074616755332333598/robin.png?width=434&height=606`

and then I want to save it in the `img_name` variable
distant burrow
#

I'm trying to use slash commands / hybrid commands for my discord bot.
It seems I can't get it to work with cogs.

Has anyone used hybrid commands before? Could you give me some tips on how to do this properly?

vital glacier
#

commands.hybrid_command()

#

if im correct

naive briar
#

!d discord.Message.attachments

unkempt canyonBOT
naive briar
#

!d discord.Attachment.url

unkempt canyonBOT
#

The attachment URL. If the message this attachment was attached to is deleted, then this will 404.

slate swan
#

thank you very muchhhh

slate swan
#

ofc this was a stupid question 😭 thank you

slate swan
#
    embed.set_thumbnail(url=ctx.guild.icon_url)
AttributeError: 'Guild' object has no attribute 'icon_url'```
vocal snow
#

!d discord.Guild

unkempt canyonBOT
#

class discord.Guild```
Represents a Discord guild.

This is referred to as a β€œserver” in the official Discord UI.

x == y Checks if two guilds are equal.

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

hash(x) Returns the guild’s hash.

str(x) Returns the guild’s name.
vocal snow
#

I guess .icon is what you want

slate swan
#

oh no need url

#

it used to be icon_url ig but it updated from _ to .

vocal snow
slate swan
#

oh thanks!

mighty jay
# distant burrow I'm trying to use slash commands / hybrid commands for my discord bot. It seems ...

A test cog

from discord.ext import commands
from discord.ext.commands import Context

# Here we name the cog and create a new class for the cog.
class Template(commands.Cog, name="template"):
    def __init__(self, bot):
        self.bot = bot

    # Here you can just add your own commands, you'll always need to provide "self" as first parameter.

    @commands.hybrid_command(
        name="test",
        description="This is a testing command that does nothing.",
    )
    async def test(self, context: Context):
        """
        This is a testing command that does nothing.

        :param context: The application command context.
        """
        await context.send("This works.")

# And then we finally add the cog to the bot so that it can load, unload, reload and use it's content.
async def setup(bot):
    await bot.add_cog(Template(bot))

To sync slash commands globally, you need to incorporate this in your bot.py or main.py equivalent:

@bot.event
async def on_ready() -> None:
    """
    The code in this event is executed when the bot is ready.
    """
    status_task.start()
    await bot.tree.sync(guild=discord.Object(id="guild id here"))

This last part ensures that you're loading it forcefully

naive briar
#

Don't run tasks and sync in on_ready

distant burrow
mighty jay
naive briar
#

Unless it was cancelled before

#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
naive briar
#

Override this method instead

deep osprey
#
#THE COMMAND
@app_commands.checks.has_any_role("Owner","Moderator")

#THE ERROR HANDLER
@test.error
async def on_test_error(interaction: discord.Interaction,error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingAnyRole):
        await interaction.response.send_message("You are not authorized to use this command!")``` The error message is not sent, just "app did not respond"
distant burrow
#

So, how exactly do I load the cogs now?

#

Because all this has just made it more, unclear

distant burrow
#

and why is it a f string

deep osprey
#

they don't matter, I removed them and nothing changed

naive briar
#

!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.
distant burrow
naive briar
#

What are you on about

distant burrow
#

I would just

await send_message("Hello", embed=Embed)```
naive briar
#

I'm just saying it's for the content of the message

distant burrow
#

and it'd always worked

naive briar
#

It's the same thing

distant burrow
#

yeah, alright, that's what I was wondering

deep osprey
#

So why doesn't it send the custom error message?

vocal snow
#

add an else clause and raise error there

deep osprey
#

the actual error is "The app did not respond" and when I added else clause, nothing happened too

vocal snow
deep osprey
#

nope

vocal snow
#

then you're probably just not responding to the interaction in time

#

what's the code for your command?

slate swan
#

i'm receiving this error in this part of the code:

                    print("detected #")
                    #mark will mark how much occurances it will be for the multi-rollings,
                    #mark will only store the first value
                    mark = args_result.split('#')
                    args_result[0] = mark[1]
                    mark.pop(1)
                    for z in range(0, mark):
                        #here will start the multi-rolling
                        print("initiating sequence")
                        resp_sub = f"{z}#"
                        for x in args_result:
                            #this is the subroll of keach multiroll from a sequence of rolls
                            print("initiating rollling")
                            roll_result = self.sub_roll(x)
                            print(roll_result)
                            resp_sub = resp_sub + f"{indice} {args_result[x]} {roll_result}"
                            store.append(roll_result[1])
                        resp_sub = + "\n"
                else:
                    #when there aren't a # it will initiate a single roll
                    resp_sub = ""
                    for x in args_result:
                        #this will be a regular roll for each dice in the line, will be stored into store
                        print("initiating rollling")
                        roll_result = self.sub_roll(x)
                        print(roll_result)
                        if not resp_sub:
                            resp_sub = f"{indice} {args_result[x]} {roll_result}"
                        else:
                            resp_sub = resp_sub + f"{indice} {args_result[x]} {roll_result}"
                        print(resp_sub)
                        store.append(roll_result[1])
                        print(store)```
#

but even i changing the type to string the error persists

#

guess it's indice

#

now i received this:
list index out of range

#

on console

sucess on habilited
initiating rollling
[[[5], 5]]
1d6 [[[5], 5]]```
light violet
#

await ch.set_permissions(ctx.guild.default_role,view_channel=True,send_messages=False)

view channel perm is edited btw why not send messages

naive briar
#

What

light violet
naive briar
#

Is not what

slate swan
#

guess i understood what was happening

#

!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
#
Sucess: Bot is connected to discord!
Ping.py is ready
Roll.py is ready
started rolling...
indz: 1
indz: d
indz: 6
['1d6']
testing # occurence
sucess on habilited
initiating rollling
[[[3], 3]]```
#

console

#

it basically stops at line 91

#

better, at line 80

deep osprey
distant burrow
#

hello, I have once again returned

#
        for f in path.glob("[!_]*.py"):
            print("Extension(s) loading...")
            await self.load_extension(f"cogs.{f.stem}")```
I have a file that ends with .py and does not begin with _
Why does it not run properly?
#

not even the printing happens, so that indicates that it doesn't see the file in the folder i specified

slate swan
#

how do i test a thing if it can be true or not?

#

or better

#

how to check if the array have array inside the array?

#
Roll.py is ready
[[0, 1], '+']
calculating rest
calculating rest
[[[0, 1], '+'], [[1, 2], '-']]
calculating rest
calculating rest```
#

the first one just had one array

#

and gave me this error:
string index out of range

#

okay nevermind

#

i found what was happening

hasty herald
#

How to send a specified post forum using webhook? Can help~?

slate swan
#

okay, why this don't work?

indice = [[[0,1], '+']]

print(indice[indx][1])
#

is there a test command?

slate swan
#

Why "{indice[indx][1]} {x}" is not working?

                        #this will be a regular roll for each dice in the line, will be stored into store
                        print(x, indx)
                        roll_result = self.sub_roll(x)
                        if not resp_sub:
                            resp_sub = f"{x}"
                            for roll_index in roll_result[0]:
                                resp_sub = resp_sub + f"({roll_index})"
                            resp_sub = resp_sub + f"[{roll_result[1]}]"
                        else:
                            resp_sub = resp_sub + f"{indice[indx][1]} {x}"
                            for roll_index in roll_result[0]:
                                resp_sub = resp_sub + f"({roll_index})"
                            resp_sub = resp_sub + f"[{roll_result[1]}]"
                        store.append(roll_result[1])
                print(resp_sub)```
#

guess now i know what hhappened

#

indz is being the next instead of previous

#

it should be indz-1

vale wing
#

@slate swan what kind of algorithm are you trying to implement

#

I've seen you struggling with it for like 4 days so far

#

And I suspect it might be xy problem

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
#

the algorythm to make operations

vale wing
#

I mean what is it supposed to do

slate swan
#

first it's suppose to calculate the division, then multiplication then sum and subtraction

#

using the indice as a reference to number position and which operand itwas using

slate swan
#

it's a dice roll algorythm

#

like roll 1d6

#

or 1d20

#

as you can see it's rolling dices:

#

the result show 3

#

at the final

#

did you got me?

vale wing
#

Nah maybe idk of dices

#

Does 1d6 mean a dice with 6 possible outcomes?

slate swan
#

yes

#

and 1d20 with 20 possible outcomes

#

and so go on

vale wing
#

What bothers you to use randint then

slate swan
#

well, because it's a function to roll the dice, to make a roll it's basically using randint

#

alll dices show interger outcomes

#

and it's also suppose to get all dices and calculation resulst and show it at final

vale wing
#

There can be unlimited amount of dices?

slate swan
#

yes

#

for example i roll 1d6+1d6, and it brings 4 and 5, so it's suppose to the final result being 9

#

I will be afk for now, i'm going to GYM, when i'm back i will see the message

#

please ping during reply

#

so i won't be lost with others

vale wing
#

Either I don't get something or you overcomplicated it

#

Lemme try and write a function for that

maiden fable
#

what do u wanna achieve?