#discord-bots

1 messages Β· Page 193 of 1

silk fulcrum
#

you can get the info you need from ther

rare vector
#

its not a disc. ban

silk fulcrum
#

huh?

rare vector
#

its for a game

silk fulcrum
#

this is quite a discord-bots server

rare vector
#

which doesnt log server bans

#

yes but im making abot

full lily
#

yeah so throw it into a database to log it

rare vector
#

to log those bans, and i thought a data base for info would be best

#

hence the question

full lily
#

i used sqlite3

silk fulcrum
#

23

#

it's a good choice if you are a beginner

full lily
#

There's Dbviewer - a gui database application that you can use for creating your tables and then any troubleshooting

silk fulcrum
full lily
#

no idea

silk fulcrum
#

sad

full lily
#

they might have their own tool

silk fulcrum
#

their own postges?

full lily
#

yes

rare vector
#

tyvm, time to read πŸ˜„

silk fulcrum
#

but i guess there is no choice

uncut flume
#
@client.command()
@commands.has_permissions(manage_guild=True)
async def toggleinv(ctx):
    guild = ctx.guild
    if guild.features.invites_disabled:
        await guild.edit(features=discord.GuildFeatures(invites=True))
        await ctx.send("Invites are now enabled in this server.")
    else:
        await guild.edit(features=discord.GuildFeatures(invites=False))
        await ctx.send("Invites are now disabled in this server.")

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'invites_disabled'

Anyone know what the right attribute is to reference if invites are disabled or not? Thought it was invites_disabled according to https://discordpy.readthedocs.io/en/stable/api.html?highlight=pause invites#discord.Guild.edit but I guess not..

upper root
#

bump on this one please

young dagger
#

How can I use queue and prevent users from joining the voice channel and from taking up someone else's spot?

pseudo saffron
#

what do i need to write on on_message at the bottom so every command is working again

pseudo saffron
#

cause guild.features is a list

rare vector
#

I am so unbelievably lost with this database stuff, i just don't know how to start

winged linden
#

I have a datetime like this 2022-12-28T15:15:02.947Z
and I would like to use this

DatetimeF = discord.utils.format_dt(dt, style="F")
pseudo saffron
#

my on_message alway activate twice per message why

#

i just have 1 bot open

slate swan
#

Who

#

!d discord.InteractionResponse.send_message the embeds kwarg

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=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
winged linden
#
ValueError: time data '2022-12-28T15:15:02.947Z' does not match format '%Y-%m-%dT%H:%M:%S:%fZ'
slate swan
#

oh

#

where'd you get that string from?

winged linden
#

Api

slate swan
#

which API?

winged linden
#

roblox api

slate swan
#

!e ```py
import datetime
print(datetime.datetime.fromisoformat( '2022-12-28T15:15:02.947Z'))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

2022-12-28 15:15:02.947000+00:00
slate swan
#

use fromisoformat

winged linden
#

i just managed to get it working but is this prefered over strptime

slate swan
#

a lot

winged linden
#

Okay

winged linden
# slate swan a lot

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

#

when I did just datetime i got

#
ValueError: Invalid isoformat string: '2022-12-28T15:15:02.947Z'
slate swan
#

did you do py import datetime or ```py
from datetime import datetime

winged linden
#

both

#

actually no

#
from datetime import datetime
``` juST THIS
slate swan
#

!e ```py
from datetime import datetime
print(datetime.fromisoformat('2022-12-28T15:15:02.947Z'))

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

2022-12-28 15:15:02.947000+00:00
winged linden
#

is it because im using a variable?

#

!e

from datetime import datetime
dt = "2022-12-28T15:15:02.947Z"
print(datetime.fromisoformat(dt))
unkempt canyonBOT
#

@winged linden :white_check_mark: Your 3.11 eval job has completed with return code 0.

2022-12-28 15:15:02.947000+00:00
winged linden
#

I wonder why mine doesn't work

ionic garden
#

can someone review this code for blackjack: https://paste.pythondiscord.com/adabidetum
i'm not sure if it's good to have a view depend on the code that calls it...
(if anyone wants the view code i can share as well)

zinc geyser
#

This is the first time I've tried using discord.py in a while, and I'm trying to set up a bot to use, but every time I try to run it, it returns this:

-  File "main.py", line 22, in <module>
-    bot.run(os.getenv("TOKEN"))
-  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 723, in run
-    return future.result()
-  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 702, in runner
-    await self.start(*args, **kwargs)
-  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 665, in start
-    await self.login(*args, bot=bot)
-  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 511, in login
-    await self.http.static_login(token.strip(), bot=bot)
-AttributeError: 'NoneType' object has no attribute 'strip'

This is where I initiated it:

bot = discord.Client(intents=intent)
load_dotenv()
bot.run(os.getenv("TOKEN"))
smoky sinew
#

no, Context is only for hybrid commands and message commands

#

you use Interaction for slash commands

slate swan
#

or you dont have it set at all

zinc geyser
#

thats what someone else said, but I do

slate swan
smoky sinew
zinc geyser
#

just cause its an err

slate swan
zinc geyser
slate swan
#

do you use python-dotenv?

zinc geyser
#

from dotenv import load_dotenv

#

outdated?

slate swan
#

and did you call the load_dotenv function? just importing it wont do anything

zinc geyser
#

yes i did

#

Nvm, my editor was just being goofy

smoky sinew
#

you can do that without a bot by using announcement channels

slate swan
#

hello

#

can someone help me with my code

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

slate swan
#

Ignoring exception in command paid_id_mines:
Traceback (most recent call last):
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 356, in paid_id_mines
await ctx.send(embed=em)
UnboundLocalError: local variable 'em' referenced before assignment

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

Traceback (most recent call last):
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: UnboundLocalError: local variable 'em' referenced before assignment
Ignoring exception in command paid_id_mines:
Traceback (most recent call last):
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/normal/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 364, in paid_id_mines
await ctx.send(embed=em2)
UnboundLocalError: local variable 'em2' referenced before assignment

#

so confusing 😭

sturdy lichen
#

anyone can help me , my code is working but it doesnt show the message i send on my server to another server.. it only shows the authors name like this on the picture

import discord

TOKEN = 'xxxxxx'
SOURCE_CHANNEL_ID = xxxxx
TARGET_CHANNEL_ID = [xxxxxx, xxxxx]

client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')

@client.event
async def on_message(message):
if message.channel.id != SOURCE_CHANNEL_ID or message.author == client.user:
return

for target_channel_id in TARGET_CHANNEL_ID:
    target_channel = client.get_channel(target_channel_id)
    await target_channel.send(f'{message.author}: {message.content}')

client.run(TOKEN)

slate swan
#

@shrewd fjord

sturdy lichen
pseudo saffron
#

how to set an add_field under a set_image ?

pseudo saffron
lone ivy
#

Hello. New to coding and Python, been using ChatGPT to help me this past month, but every time i feel like im getting somewhere, i feel like i hit a point of no return where i have to restart. I'm wanting to code my own custom Pokemon discord bot, and am curious where'd be the best place to ask for help. Would it be here or in the #1035199133436354600 and just create a thread?

pseudo saffron
#

when you are new to py

lone ivy
#

not the kind of attitude i'm looking for, i will look elsewhere then, thanks πŸ™‚

smoky sinew
smoky sinew
smoky sinew
lone ivy
#

So i'm creating a Pokemon class, and i'm adding attributes and methods. My current problem is i've seen attack as both and attribute and as a method, but never both, so i'm curious if there's any specific benefit to either just have it as an attribute, or as a method

#

think i just answered my own question typing it out lol

#

attack attribute is the attack stat where the method is the actual action of attack

pseudo saffron
pseudo saffron
smoky sinew
#

what do you mean?

pseudo saffron
#

wait

#

it like you punching someone with a gif

#

and hte field should say who has won the fight

smoky sinew
#

ok

pseudo saffron
#

so a thumbnail kinda wouldnt be nice for it

#

i think

smoky sinew
#

why don't you just add it above

naive briar
#

Then just use set_image, what's bad about it

smoky sinew
#

he wants to add a field below the image

pseudo saffron
#

and i think a footer would be to small

naive briar
#

Footer exists

smoky sinew
#

just put the field above the image

naive briar
#

Then there's no way

smoky sinew
#

or use the description

pseudo saffron
#

yeah i am cool with it

#

just wondered if it possible

smoky sinew
pseudo saffron
#

so it would literlly spam without it

#

ah he has it already

#

didnt read the client.user thing

#

but it still would be activated by other bots

smoky sinew
slate swan
#

is False is much more preferable than either

#

is False > == False > not

#

await client.wait_for("message",check=check) doesnt work, it just detects " "

#

you don't have message_content intents

#

or a badly configured check predicate

smoky sinew
slate swan
slate swan
# smoky sinew why?

not x can be true even if x is "" () [] or 0
== False can be true even if x is 0

graceful ermine
#

I have been working on this for the past 20 min how could I fix it?

I'm trying to make the but log the ticket transcript into a channel

#

error:
TypeError: Guild.get_channel() got some positional-only arguments passed as keyword arguments: 'chan

#

@slate swan could you help?

smoky sinew
slate swan
slate swan
#

not a keyword argument

pseudo saffron
smoky sinew
smoky sinew
slate swan
#

im talking in general

pseudo saffron
slate swan
#

is bool is mostly more preferable than not

smoky sinew
#

how

slate swan
#

!e ```py
async def foo():
return False

if not foo():
print("yes")
else:
print("No")

unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | <string>:4: RuntimeWarning: coroutine 'foo' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
003 | No
slate swan
#

if foo() is False was used here it might atleast catch attention of the user

#

not x is safe to use where the return type is fixed to be bool yeah

fading marlin
slate swan
#

if it works , it works, lol.

shrewd fjord
#

Kek

unkempt mauve
#

what is the inline thing

pulsar bridge
#

Is it possible to have nested groups?
Like, a command inside a group inside a group?

class Group1(app_commands.Group):
  
  class Group2(app_commands.Group):

    @app_commands.command(name='command')
    async def stuff(interaction: discord.Interaction)
    '''Do Stuff'''

Like that?
If so, how would you initialize it?

Groupdef = Group1(name='group', description = 'Group for dealing with x commands.')
client.tree.add_command(Groupdef)

Like that?

slate swan
naive briar
#

Why

unkempt mauve
# slate swan

if the inline equals to the boolean True. will it be like one under another under another right

naive briar
#

Did you even look at it

slate swan
#

inline means in same line
non-inline means in different line

unkempt mauve
#

oh

slate swan
#

in-line

naive briar
#

Just create subcommand, and no one declares classes like that

pulsar bridge
#

it's how I was taught
If you have a better solution, I'm all ears

slate swan
#

its possible to have sub groups in slash commands ( supported officially by discord api ) but discord.py'a app command system is under documented lol

pulsar bridge
slate swan
#

class inside a class is evil stitch_sob

naive briar
#

I remember there's a deco for subcomamnd

pulsar bridge
#

@slate swan
Evil, you say?

oh wait, you were there
my bad

pulsar bridge
unkempt mauve
#

what is the function for server counts and members count

pulsar bridge
slate swan
#

if you wanna use hikari, totally yeah

#

you'll have to rewrite all your discord related code tho 🚢

#

Can I set up multiple bots on one linux vps? Like I'd just create another service ?

smoky sinew
#

yes

#

actually im not sure

#

probably

slate swan
#

😭

#

🚢 you can ofc run multiple tasks in a vps

slate swan
smoky sinew
slate swan
slate swan
#

but you won't really get ratelimited as long as you're not doing something fishy

sturdy lichen
#

I need help about my code , unique roles are pinging multiple times aniblobsweat aniblobsweat

#

I tried putting previous_messages already

shrewd fjord
harsh egret
#

im trying to get back in coding and everytime i run my code it says this:

sturdy lichen
slate swan
#

is there a way for discord.py to see recent vanity url code activity?

async def on_guild_update(self, before: vanity_url_code, after: vanity_url_code):```
this example doesn't work, says its not defined.
#

because the example doesnt exist anywhere

#

its my example, ive tried it

#

the typehint should be discord.Guild

#

didnt work as planned

#

ah i will try that

#

and then you check before.vanity_url and after.vanity_url

#

!d discord.Guild.vanity_url

unkempt canyonBOT
#

property vanity_url```
The Discord vanity invite URL for this guild, if available.

New in version 2.0.
shrewd apex
upbeat otter
hard olive
#

I want to make a discord bot to play music, I'm just a beginner in python, i can only do basic stuff.
Can someone help me?
I just want basic features like, play , pause, skip , from YT. & Spotify.

naive briar
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
hard olive
#

Ok not YT or Spotify.
I want to make a discord bot to play music from my local files to VC, I'm just a beginner in python, i can only do basic stuff.
Can someone help me?

radiant bough
#

If there are emojis in an embed which the bot can’t access will the embed be sent?

shrewd apex
#

learn oop async programming

#

and*

radiant bough
#

a?help (command / cog name) works but somehow nothing comes when I use a?help

shrewd apex
#

send_bot_help iirc

radiant bough
#

….

#

I have default one

#

but in a better way

#

Or subclass

loud junco
#
class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(aliases = ['leave'])
    @commands.cooldown(1, 1, commands.BucketType.user)
    async def quit(self, ctx):
        dbfunc = self.bot.database_handler
        userid = ctx.author.id
        cid = ctx.channel.id
        match = await Match(ctx)
        playerlist = await Playerlist(ctx)
        is_quitting = False
        created = await self.bot.db.fetch('SELECT * FROM match WHERE matchid = $1', cid)
        
        if created == []:
            await ctx.send(f'**{username}**, game has not been created')
        else:
            if userid == match['matchhostid']:
                await ctx.send(f'**{username}**, you do know `ep stop` exist for some reason?')
            else:
                if userid == playerlist['player1id']:
                    await dbfunc.setIntValue('player1id', 'playerlist', cid, 1, 'matchid')
                    is_quitting == True
                elif userid == playerlist['player2id']:
                    await dbfunc.setIntValue('player2id', 'playerlist', cid, 1, 'matchid')
                    is_quitting == True
                elif userid == playerlist['player3id']:
                    await dbfunc.setIntValue('player3id', 'playerlist', cid, 1, 'matchid')
                    is_quitting == True
                elif userid == playerlist['player4id']:
                    await dbfunc.setIntValue('player4id', 'playerlist', cid, 1, 'matchid')
                    is_quitting == True
                else:
                    await ctx.send(f'**{username}**, you are not in the game')
                    
            if is_quitting == True: 
                await self.bot.db.execute('''
    DELETE FROM playercard
    WHERE playerid = $1
''',userid)
                await ctx.send(f'**{username}**, you had left the game successfully')


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

why is this chungus not working

#

match['matchhostid'] = my userid
no error btw

radiant bough
naive briar
loud junco
#

it returns nothing
not even error

bright wedge
loud junco
#

but do u guys have any ideas on how to compress the code?

#

it looks very messy

#

aight

loud junco
#

but why is it not showing undefined error

cloud dawn
loud junco
#

and also only 4 lines are repeated

#

HEHEHE

cloud dawn
# loud junco thats why im asking if anyone has any idea on how to compress it
class MyCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(aliases = ['leave'])
    @commands.cooldown(1, 1, commands.BucketType.user)
    async def quit(self, ctx):
        cid = ctx.channel.id

        created = await self.bot.db.fetch('SELECT * FROM match WHERE matchid = $1', cid)
        if created == []:
            await ctx.send(f'**{username}**, game has not been created')
            return

        userid = ctx.author.id
        if userid == (await Match(ctx))['matchhostid']:
            await ctx.send(f'**{username}**, you do know `ep stop` exist for some reason?')
            return

        playerlist = await Playerlist(ctx)
        plist = [playerlist[f'player{i}id'] for i in range(1, 5)]

        if userid in plist:
            player = plist.index(userid) + 1
            await self.bot.database_handler.setIntValue(f'player{player}id', 'playerlist', cid, 1, 'matchid')
            await self.bot.db.execute('DELETE FROM playercard WHERE playerid = $1', userid)
            await ctx.send(f'**{username}**, you had left the game successfully')
        else:
            await ctx.send(f'**{username}**, you are not in the game')


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

playerlist returning a dict is a violation.

loud junco
#

AHEM

loud junco
cloud dawn
#

I cry

loud junco
#

dont

#

btw

cloud dawn
#

Function starting with a capital letter pepecry

loud junco
#

how do u make timestamp

loud junco
cloud dawn
#

<t:12812912819:R>

#

Those?

#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
cloud dawn
#

!d discord.utils.format_dt

loud junco
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...
loud junco
#

im about to ping u

cloud dawn
#

<t:12812912819:R>
But I recommend the function, way more readable.

cloud dawn
loud junco
#

wtf is 12812912819

#

ddmmyyyy?

shrewd apex
#

timestamp

cloud dawn
#

Dunno I smashed my hand against the keyboard.

loud junco
#

oof

#

how do u control the number

cloud dawn
#

But it's a unix timestamp yeah

shrewd apex
#

supposed to be a timestamp

cloud dawn
#

<t:12812912819:F>

loud junco
#

huh

cloud dawn
#

Magic

loud junco
#

what does the number stand for

cloud dawn
loud junco
#

WTF

cloud dawn
#

<t:0:R>

#

Aka <t:0:R>

naive briar
#

<t:0:F>

patent marlin
#

how do I use a list here?

if message.content.startswith(list):
    pass
naive briar
#

Iterate over the list

loud junco
#

who thought using 1970 will be a good idea

cloud dawn
patent marlin
#

ah ok, thanks

naive briar
#

And don't override a built-in functions with a variable

naive briar
loud junco
#

the number is going to be so big

cloud dawn
cloud dawn
#

10*xEn

brazen raft
pliant gulch
#

Clocks dropping the new DLC package after 64-bit @ year 292,277,026,596, december 4th

#

Also the sun is supposed to run out of hydrogen in like, 5-6 billion years

cold sonnet
#

no worries the banks don't run out of hydrogen, the sun can just take a loan

gentle nova
#

possible to print out what kind of permission user have ?

naive briar
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
gentle nova
#

guild perms i know, need user

naive briar
#

What

gentle nova
#

i need user permisisons not guild permissions

naive briar
#

That is the member's permissions in the guild that member object is from

#

Read the embed

gentle nova
#

so i need user.has_permissions convert to guild.member.haS_permissions ?

#

not working in nextcord.

loud junco
#

is random wrong

#

!d random

unkempt canyonBOT
#

Source code: Lib/random.py

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

naive briar
#

It's a built-in library, so it doesn't need to be in that file

loud junco
#

oo

stuck flare
#

is there any good tutorials for making a disc bot?

shrewd fjord
#

Docs πŸ—Ώ

stuck flare
shrewd fjord
#

Or use some walkthrough on github, as because i am saying yt isnt always up to date with the updates

gentle nova
#

@shrewd fjorddo you know how to do command cd with database and check it if command cd ends ?

shrewd fjord
shrewd fjord
#

What's your goal?

#

Just tell it.

gentle nova
#

Connect my command to database , log users who used command, who got hit by the command , and check cooldown for user

shrewd fjord
shrewd fjord
stuck flare
shrewd fjord
#

dict={
something: some value,
}

shrewd fjord
#

It's depends on ur purposes

naive briar
#

Hikari has low level API so it kinda gives you more control

gentle nova
#

Im trying to make fully functional command to add one day economic to it , and currency. That currency will be server money . While u chatting you earn some money and talking with people in voice.

#

So that's why i need to find a way to do database for future things

stuck flare
naive briar
#

It makes your projects cleaner, but it's not required

shrewd fjord
gentle nova
#

im trying with pymongo

shrewd fjord
#

But first of all u need yi learn the query anyway

naive briar
#

pymongo is blocking

shrewd fjord
gentle nova
#

@naive briarcoulndt find tutorial with sql3

stuck flare
shrewd fjord
#

sqlbolt πŸ‘€

shrewd fjord
stuck flare
gentle nova
#

@shrewd fjordThis database thing have any common to python ?

shrewd fjord
naive briar
#

Same thing

shrewd fjord
gentle nova
#

@shrewd fjordmy brains exploded already πŸ˜„

stuck flare
#

am in a venv now @shrewd fjord

shrewd fjord
#

Now install packages

stuck flare
shrewd fjord
#

Imma gtg, catglal here anyways :)

gentle nova
#

Catgal can you give me begining of database thing ?

quick gust
#

how would I make a custom cooldown? I basically want to exempt a user from the cooldown if they have voted for the bot in the past x hours (disnake)

gentle nova
#
@cooldowns.cooldown(1, 300, bucket=cooldowns.SlashBucket.author)```
quick gust
#

custom cooldown

naive briar
unkempt canyonBOT
#
Fat chance.

No documentation found for the requested symbol.

naive briar
naive briar
#

Probably

quick gust
#

alright

#

im guessing I can just pass a check to cooldown

stuck flare
#

Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
i get this error in my venv when i try to run the disc bot code

upbeat otter
#

in your venv files

shrewd fjord
#

totally not laughing

#

Ayo mods, is bullying allowed in this server (bullying a friend specially)

naive umbra
shrewd fjord
#

Sed, ifernum, you safe here >:)

shrewd apex
# quick gust **custom cooldown**

make a temporary cache subclass dict or UserDict then override setitem, getitem and contains and run some check expired time function then update and make a decorator wrapper or use commands.check

quick gust
#

Mmm alright thanks!

static holly
#

hi, i copy a tutorial via a YT video and i have a error:

@commands.Cog.listener()
    async def on_message(message):
        if message.author.bot:
            return
        author= message.author
        guild=message.guild
        async with bot.db.cursor() as cursor:
            await cursor.execute ("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
            xp = await cursor.fetchone()
            await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
            level = await cursor.fetchone()

Traceback (most recent call last): File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ TypeError: levelup.on_message() takes 1 positional argument but 2 were given

gloomy flint
#
async def on_message(self, message)```
static holly
#

okay! πŸ™‚

static holly
#
@commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        author= message.author
        guild=message.guild
        async with bot.db.cursor() as cursor:
            await cursor.execute ("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
            xp = await cursor.fetchone()
            await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
            level = await cursor.fetchone()
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\level_system\leveling.py", line 31, in on_message
    async with bot.db.cursor() as cursor:
               ^^^^^^
AttributeError: 'Bot' object has no attribute 'db'
#

self.bot?

gloomy flint
#

Yes

static holly
# gloomy flint Yes
    async with self.bot.db.cursor() as cursor:
               ^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'db'```
cold sonnet
#

stop copying yt tutorials

gloomy flint
#

What kind of db ?

static holly
gloomy flint
static holly
gloomy flint
#

You have to write you down in the vi so that you can use it later

cold sonnet
#
  1. copying is shit
  2. dpy yt tutorials are shit
static holly
#

if you say so

ionic garden
#

how do i have a view do some stuff when it starts up in __init__?

shrewd apex
#

i would just subclass the view

ionic garden
#

so like

#

i have an embed and some buttons that change said embed

#

i want the embed to have different startups depending on an argument

slate swan
#

use callback ?

#

!d discord.ui.Button.callback

unkempt canyonBOT
#

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

The callback associated with this UI item.

This can be overridden by subclasses.
unkempt canyonBOT
#

Hey @uncut flume!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

uncut flume
full lily
#

also you have an error in your error handler

#

what does ModerationCog.on_application_command_error look like?

uncut flume
#

it's actually AttributeError: 'Context' object has no attribute 'ban'

uncut flume
# full lily what does `ModerationCog.on_application_command_error` look like?
 @ban.error
    async def on_application_command_error(ctx, error: discord.DiscordException):
        if isinstance(error, commands.MissingRequiredArgument):
            embed = discord.Embed(
            title=':no_entry_sign: Missing Argument',
            color=discord.Color.red()
            )
            embed.add_field(name='Uh oh!',value='Member is a required argument that is missing.', inline=False)
            await ctx.channel.send(embed=embed)
        else:
            raise error  # Here we raise other errors to ensure they aren't ignored
vivid drift
#

hello i try to make a discord bot with python i start it but anythings work but the bot is online. what i need to do?

uncut flume
full lily
#

the function

hushed galleon
#

seems like you're missing self as the first argument, so nextcord is passing the Context object to the member parameter instead

sturdy lichen
#

hi, where can i deploy my bot after coding? to make it run all the time

uncut flume
#

thank you

whole sparrow
#

How do I get forum posts when a new forum post is just made?

silk fulcrum
#

what's the problem?

vivid drift
fair marsh
#

`copy_ID_01 = "xxxxxxxxxxxxxxxxxx1"
copy_ID_02 = "xxxxxxxxxxxxxxxxxx2"

first = "#role <@"
second ="> police , rank1"

import requests
#Webhook of my channel.
mUrl = "httpxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

data = {"content": (first)+(copy_ID_01)+(second)}
data = {"content": (first)+(copy_ID_02)+(second)}

response = requests.post(mUrl, json=data)
print(response.status_code)
print(response.content)`


when I run
my webhook send only the second message I don't understand why is only sending the second message

fair marsh
ionic garden
graceful ermine
#

How do I fix this>

#

?*

#
@bot.event
async def on_ready():
    print(f"we are logged in as {bot.user}")
    for fn in os.listdir("./cogs"):
        if fn.endswith(".py"):
            await bot.load_extension(f"cogs.{fn[:-3]}")```
rough wave
#

Your last line of code doesn't work

graceful ermine
#

how?

#

when I remove the await it says I need to await it which is weird

#

and I added @bot.event because I needed a async function to put the await command in there

#

@rough wave

rough wave
#

"Object NoneType can't be used in 'await' extension"

#

I don't know

torn sail
graceful ermine
#

No

#

@torn sail

#

this is what it looks like

whole sparrow
#

How do I get a forum post title and message with discord.py?

smoky sinew
#

so you'd get the thread object

#

and use .name

whole sparrow
#

Is there a way to get the thread/forum post when created?

whole sparrow
#

oo. is this an event listener where I can just do async def on_thread_join?

smoky sinew
#

it is an event yes

whole sparrow
#

Thanks man you're the best

smoky sinew
#

no problem

torn sail
smoky sinew
whole sparrow
#

Is it possible for bot to send dm's to user's who has no dm's setting

whole sparrow
#

πŸ‘

ivory wraith
#

discord.py 2.1.0, python 3.11.1.

if I have a interaction command (in a GroupCog):

@discord.app_commands.command(name="test")
async def test(self, interaction, param1, param2, param3):
  params = [param1, param2, param3]
  await interaction.response.send_message("Hello!", view=TestButtonView())

and I want to attach a button to it (this is currently outside the GroupCog):

class TestButtonView(discord.ui.View):
  @discord.ui.button(label="Testing Button")
  async def test_button(self, interaction, button):
    await interaction.response.send_message("How are you?")

is there any way to get the params list from the test command to use in the test_button's processing or response? for example, if I want to send the params list when the button is clicked, could I get the list to use in the response?

sick birch
ivory wraith
#

a lot more simple than i thought it would be, thanks!

ivory wraith
# sick birch Sure. Create an `__init__` for `TestButtonView`, that accepts a list of the para...

so, now I did (the equivalent of):

class TestButtonView(discord.ui.View):
  def __init__(self, params):
    self.params = params

  @discord.ui.button(label="Testing Button")
  async def test_button(self, interaction, button):
    await interaction.response.send_message("How are you?" + params)
@discord.app_commands.command(name="test")
async def test(self, interaction, param1, param2, param3):
  params = [param1, param2, param3]
  await interaction.response.send_message("Hello!", view=TestButtonView(params))

and I get this:

discord.app_commands.errors.CommandInvokeError: Command 'start' raised an exception: AttributeError: 'TestButtonView' object has no attribute '_children'
hallow rampart
#

Attribute error

ivory wraith
#

yes

fading marlin
#

You have to init the superclass too

ivory wraith
#

ah

fading marlin
#

That's not how you access instance attributes either (looking at the button callback). You have to use the instance argument to access the attributes

sick birch
ivory wraith
#

i did do the self.params in my actual code, i made a typo in the example
the super().__init__() helped, though - thanks

ancient pulsar
#

I think I am ready now after 5k days learning non-stop

fading marlin
#

Those are a lot of years

loud junco
#

something aint right

fading marlin
#

🀷

loud junco
#

(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻

unkempt canyonBOT
#

Hey @uncut flume!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

uncut flume
loud junco
#

i think this will fix it

fading marlin
whole sparrow
#

how do i make a background task that doesnt loop which I can start/stop whenever

pseudo saffron
#

how toi set bot variables

#

i tried

#

bot.variable = 0 but it says attribute error

fading marlin
#

You're probably trying to access the attribute before you define it

fading marlin
pseudo saffron
radiant bough
#

What could be the reason behind my main help command a?help not sending anything but if I use a?help (command / cog name) it works

#

I’ve subclassed the help command btw

#

Don’t get any error when I run a?help

golden portal
#

could be a suppressed error

wooden glade
harsh egret
#

im getting back into coding and im so confused on whats the problem here

vale wing
#

Regenerate token, you just leaked it

smoky sinew
#

you have your token in there

smoky sinew
#

also you missed the actual error part

harsh egret
#

i just have client.event

harsh egret
vale wing
#

It is a decorator

harsh egret
#

if i do @client.event() it gives me this error

smoky sinew
#

just do @client.event

vale wing
#

Yeah that's why you are supposed to do @client.event

smoky sinew
#

@client.event and @client.event() are two different things

vale wing
#

Actually best to use @client.listen()

harsh egret
#

it gives me this error

naive briar
#

Read the error

#

That's the answer, straight up

vale wing
#

!code could you please send errors in codeblock in the future, images might be difficult to read

unkempt canyonBOT
#

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.

naive briar
#

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

harsh egret
# vale wing !code could you please send errors in codeblock in the future, images might be d...
Traceback (most recent call last):
  File "c:\Users\kiril\OneDrive\Desktop\Discord bot\main.py", line 15, in <module>
    client.run("tokens in here")
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 828, in run
    asyncio.run(runner())
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 746, in start
    await self.connect(reconnect=reconnect)
  File "D:\Users\kiril\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 672, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
vale wing
#

Thanks, actually your question already was answered to

harsh egret
#

oh mb i didnt notice that ty

smoky sinew
lethal bloom
#

In Python, is there a way to count all the commands that can be executed? And that by console send me the results

smoky sinew
#

bot.walk_commands()

#

is one way you could do it

lethal bloom
#

ok

lethal bloom
smoky sinew
#

you'd probably want to get their names

#

not even sure that code will work anyways

unkempt mauve
#

need help with argument

#

in slash commands

#

I want the user to type in an argument that is either mandatory or optional. for example /choosenumber 1st Number: 69 2nd Number: 420

vale wing
unkempt mauve
#

how do I either make it mandatory or optional as well?

vale wing
#

By setting default value

#

Again I am unsure if that's proper way cause I don't use dpy, that seems logical but you should check or ask someone with experience

smoky sinew
#

like the user can fill it out or not

unkempt mauve
#

yk what I mean

unkempt mauve
shrewd apex
#

no?

#

only whether a default argument is supplied

unkempt mauve
#

The bot can't choose without any number (int)

shrewd apex
#

not adding a default argument makes it mandatory

unkempt mauve
#

can you give me example?

#

example are easier to understand

shrewd apex
naive briar
#

It's basic Python ducky_sphere

unkempt mauve
shrewd apex
#

no i meant ur usecase

loud junco
#

how do i even save playerlist in a list in database

unkempt mauve
#

I want the argument to be mandatory and I didn't get it what you meant by not adding a default argument

loud junco
#

(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻

shrewd apex
#

also u said "mandatory and optional" how does that even work

#

async def foo(inter, a: int) this makes a mandatory

shrewd apex
unkempt mauve
naive briar
#
def foo(bar: str):
    #        ^^^ required arg
def foo(bar: str = None):
    #        ^^^ optional arg
loud junco
#

i tried googling and got no result

shrewd apex
#

postgresql TEXT[]

unkempt mauve
naive briar
#

What???

shrewd apex
#

lmao

naive briar
#

Both of them are required

unkempt mauve
#

can I stream and show you

#

@naive briar I can clearly see it is optional

naive briar
#

Because you make it?

unkempt mauve
naive briar
#

I can also clearly see the default values

#

Then remove the default values

#

What's hard about that

unkempt mauve
#

the problem is I am not getting your words

#

it isn't going into my brain

shrewd apex
#

= 0 remove that

unkempt mauve
#

ok

#

lmfao I am dumb asf

#

I hate my life

radiant bough
golden portal
radiant bough
#

k

#

Can I send it here later, don’t have my laptop rn

golden portal
#

oke

sturdy shadow
#
import discord
from discord.ext import commands
from discord import app_commands, SelectOption
from discord.app_commands import Choice
from discord.ui import View

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

@bot.event
async def on_ready():
    print(f"Started {bot.user}")

@bot.command()
async def fight(interaction: discord.Interaction):
    class SelectView(View):
        @discord.ui.select(placeholder='Select Weapon', options=[
            SelectOption(label='Gun', value='gun'),
            SelectOption(label='Knife', value='knife'),
            SelectOption(label='Pill', value='pill')
        ])

        async def select_callback(self, interaction, select):
            if select.values[0] == 'gun':
                await interaction.response.send_message('Gun')
            if select.values[0] == 'knife':
                await interaction.response.send_message('Knife')
            if select.values[0] == 'pill':
                await interaction.response.send_message('Pill')

    view = SelectView()
    await interaction.response.send_message(view=view)

bot.run('token') ```
#
Traceback (most recent call last):
  File "C:\Users\Xmich\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\Xmich\OneDrive\Desktop\New folder\Website\main.py", line 31, in fight
    await interaction.response.send_message(view=view)
AttributeError: 'Context' object has no attribute 'response'

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

Traceback (most recent call last):
  File "C:\Users\Xmich\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\Xmich\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\Xmich\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: 'Context' object has no attribute 'response'```
smoky sinew
unkempt mauve
#

y bulli me

smoky sinew
#

that's not bullying

unkempt mauve
smoky sinew
vale wing
#

And why define a class inside a function

#

Smh these tutorials are really going wild if that's from tutorial

naive briar
#

Don't they have always been like this

unkempt mauve
smoky sinew
vale wing
#

They always have been cringe, but mostly because they did commands in on_message or used some constructions that "work" but break all possible code styles and principles, but class in a function is something outstanding

#

Not in this case

shrewd fjord
shrewd apex
merry cliff
slate swan
loud junco
golden portal
#

and then you would do await ctx.send(...)

loud junco
#

@shrewd apex ;-;

sturdy shadow
#

I see alright thanks

naive briar
loud junco
slate swan
loud junco
#

oo wait

#

its square bracket right?
the mutable ones

#

i did it somehow

slate swan
#

Array might be a constraint probably if it doesn't work directly

loud junco
slate swan
#

i guess

#

with python drivers you usually do it like ```py
"create table hello ( var INTEGER ARRAY);"

loud junco
#

forget it

#

at least i can get list now

#

look at what bullshit i had been through

slate swan
#

totally a bozo

loud junco
shrewd fjord
#

Why not use uppercase πŸ—Ώ

slate swan
#

on phone, too lazy

shrewd fjord
#

Bro

#

I code in phone, and made a whole db structure with uppercase in phone

#

Dont be lazy ass kek

slate swan
#

we both know that code sucks

shrewd fjord
sturdy shadow
shrewd fjord
golden portal
#

pree much, the default timeout is 180 seconds, so could just do view = SelectView(timeout=None) as well

shrewd fjord
#

Both works kek

sturdy shadow
#

thank you both

unkempt mauve
#
@tree.command(name = 'guessinggame', description = 'Starts a guessing number game.')
async def guess(interaction, number: int):
  emb = discord.Embed(title = 'Guess the number!', description = f'{interaction.user} has started a number guessing game!')
  await interaction.response.send_message(embed=emb)
  response = await client.wait_for('message')
  guess = int(response.content)
  if guess > number:
    await interaction.response.send_message('bigger')
  elif guess < number:
    await interaction.response.send_message('smaller')
  else:
    await interaction.response.send_message("You have guessed the number!")```
Having problem
shrewd fjord
#

Ye.

unkempt mauve
vale wing
sturdy shadow
#

Like whats the error

unkempt mauve
#
Traceback (most recent call last):
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 26, in guess
    guess = int(response.content)
ValueError: invalid literal for int() with base 10: ''

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

Traceback (most recent call last):
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'guessinggame' raised an exception: ValueError: invalid literal for int() with base 10: ''```
#

thats the error

vale wing
#

Argument that is incoversible to int provided

unkempt mauve
#

oh I get it

vale wing
#

What is command function signature and how you use it

unkempt mauve
#

the number is already int

#

so another int could be the issue right

vale wing
#

You provided an empty string to there

unkempt mauve
#

where

vale wing
unkempt mauve
#

wdym

light violet
#

atc = message.embeds[0].attachments[0]

how do i get the embed image

vale wing
#

Command signature is its name, arguments and typehints

light violet
#

help me pls

vale wing
unkempt canyonBOT
#

class discord.Attachment```
Represents an attachment from Discord.

str(x) Returns the URL of the attachment.

x == y Checks if the attachment is equal to another attachment.

x != y Checks if the attachment is not equal to another attachment.

hash(x) Returns the hash of the attachment.

Changed in version 1.7: Attachment can now be casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") and is hashable.
vale wing
#

Use one that you need

light violet
vale wing
#

Where exactly to embed

#

You need attachment's URL I guess

light violet
# vale wing Where exactly to embed

its an event

async def on_message(message):
  if message.author.id not in [825617171589759006,834500417014071356]:
    return
  else:
    atc =  message.embeds[0].attachments[0]
    print(atc.url)```
vale wing
#

Yeah and put this URL to corresponding place

naive briar
#

!d discord.Embed.image

unkempt canyonBOT
#

property image```
Returns an `EmbedProxy` denoting the image contents.

Possible attributes you can access are...
vale wing
#

Oh wait you can't have attachments in embed

#

My logic is erroring

golden portal
shrewd apex
#

i meant as to restrict access to the class and limit scope my bad πŸ’€

shrewd apex
sturdy shadow
#

@golden portal How can I make it where when they select a option from the menu it shows another menu which is only available to see for the person who selected it

light violet
golden portal
sturdy shadow
#

so in the SelectOption I'll add ephermeral=True?

naive briar
#

No, in the callback

vale wing
#

In send

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, 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.
sturdy shadow
#

ah I see

#

thanks guys

naive briar
#

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

sturdy shadow
#

What would be the proper way of making it show another menu. I don't see a way to do it

unkempt mauve
#

now the error is that it is already been responded

naive briar
#

!d discord.InteractionResponse read the docs

unkempt canyonBOT
#

class discord.InteractionResponse```
Represents a Discord interaction response.

This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").

New in version 2.0.
naive briar
#

The response can only be used once

#

!d discord.Interaction.followup

unkempt canyonBOT
unkempt mauve
#

theres too many options in the docs

vale wing
#

Just use disnake πŸ€“πŸ‘

unkempt mauve
#

noty

vale wing
#

We don't have inter.response.send_message (as main method), we have inter.send with automatic followup handling

#

We have response and followup too, if you need them

naive briar
#

Not like it's hard to subclass and make that in discord.py 🀷

vale wing
#

The design is very human

sturdy shadow
unkempt mauve
#

I am dumb

unkempt mauve
vale wing
#

Disnake is for lazy developers

#

And newcomers

unkempt mauve
#

okay, I gtg.. will come back to eat my brain by this

vale wing
#

And they don't have setup_hook, you gotta override start, but that's not a big deal

vale wing
polar ice
#

Any ideas why on_listen isnt working for me. im trying to print the string and its empty?


    if setup_progress[message.guild.id] == 1:
        print(message.content)
        if message.content.isnumeric() and len(message) == 8:```
#

Im using pycord πŸ™‚

slate swan
#

there's nothing like on_listen

#

do you mean on_message?

#

if so, you're missing message_content intents

sturdy shadow
#
@bot.command()
async def shop(ctx):
    class GunView(View):
        @discord.ui.select(placeholder='Select Gun', options=[
            SelectOption(label='Glock', value='gun1'),
            SelectOption(label='Pistol', value='gun2')
        ])

        async def select_callback(self, interaction, select):
            if select.values[0] == 'gun1':
                await interaction.response.send_message("Gun 1")
            if select.values[0] == 'gun2':
                await interaction.response.send_message("Gun 2")

    class SelectView(View):
        @discord.ui.select(placeholder='Select Weapon', options=[
            SelectOption(label='Spray Paint ($15)', value='spraypaint'),
            SelectOption(label='Gun ($10)', value='gun'),
            SelectOption(label='Knife ($5)', value='knife'),
            SelectOption(label='Pill ($5)', value='pill'),
        ])

        async def select_callback(self, interaction, select):
            if select.values[0] == 'spraypaint':
                await interaction.response.send_message('Spray Paint')
            if select.values[0] == 'gun':
                view = GunView()
                await ctx.send(view=view)
            if select.values[0] == 'knife':
                await interaction.response.send_message('Knife')
            if select.values[0] == 'pill':
                await interaction.response.send_message('Pill')

    view = SelectView(timeout=None)
    await ctx.send(view=view)```
#

No error but the interaction (first one) says interaction failed

#

after about 10 seconds

#

It works fine just for some reason is doing interaction failed

polar ice
#

@slate swan Sorry yeah, its late πŸ˜„ py @bot.listen("on_message") async def on_message(message): if message.author.id == bot.user.id: return # make sure the bot doesn't reply to itself, that would be silly! print(message.content) if setup_progress[message.guild.id] == 1: print(message.content) if message.content.isnumeric() and len(message) == 8: # message.content.startswith("https://www.battlemetrics.com" or "www.battlemetrics.com" or await message.respond(f"Awesome, So i have your battle metrics ID as follows: https://www.battlemetrics.com/{message}\n" f"Please double check that link is correct now, Its best to get it correct the first time!") print('works?') else: await message.reply('Seems to be an error?') print(message.content)

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

enable message_content intents

polar ice
#

@slate swan I already have, py intents = discord.Intents(message_content=True) bot = discord.Bot(intents=intents)

sturdy shadow
#

did you enable intents on the bot app

polar ice
#

Yes :/

sturdy shadow
#

No Idea I just enable all the intents

polar ice
#

want me to paste my code? ive just started, its tiny πŸ˜„

#

tried that also

civic fractal
#

for example, you probably want to enable the messages intent

#

discord.Intents(messages=True, message_content=True)

polar ice
#

@civic fractal could i just use intents = discord.Intents().all() ?

civic fractal
#

discord.Intents.all()

sturdy shadow
#

^

civic fractal
#

sure, you could

#

beware that it will use extra bandwidth that way

polar ice
#

Ill give it a try, sure ive tried this already though πŸ˜„

civic fractal
#

Also what have you done to debug this? Have you verified that your bot is connected at all? Is it receiving message notifications?

polar ice
#

Awesome, worked a dream

slate swan
civic fractal
polar ice
#

awesome, cheers guys

sturdy shadow
#
@bot.command()
async def shop(ctx):
    class GunView(View):
        @discord.ui.select(placeholder='Select Gun', options=[
            SelectOption(label='Glock', value='gun1'),
            SelectOption(label='Pistol', value='gun2')
        ])

        async def select_callback(self, interaction, select):
            if select.values[0] == 'gun1':
                await interaction.response.send_message("Gun 1")
            if select.values[0] == 'gun2':
                await interaction.response.send_message("Gun 2")

    class SelectView(View):
        @discord.ui.select(placeholder='Select Weapon', options=[
            SelectOption(label='Spray Paint ($15)', value='spraypaint'),
            SelectOption(label='Gun ($10)', value='gun'),
            SelectOption(label='Knife ($5)', value='knife'),
            SelectOption(label='Pill ($5)', value='pill'),
        ])

        async def select_callback(self, interaction, select):
            if select.values[0] == 'spraypaint':
                await interaction.response.send_message('Spray Paint')
            if select.values[0] == 'gun':
                view = GunView()
                await ctx.send(view=view)
            if select.values[0] == 'knife':
                await interaction.response.send_message('Knife')
            if select.values[0] == 'pill':
                await interaction.response.send_message('Pill')

    view = SelectView(timeout=None)
    await ctx.send(view=view)```
#

No error but the interaction (first one) says interaction failed
after about 10 seconds
It works fine just for some reason is doing interaction failed

vocal snow
#

you should be responding to the interaction there

#

with send_message

#

and I would move the classes outside of the command callback

idle dagger
#

this is from photography server. they have image competitions where users can upload picture and then other members can vote. is there a way to hide the vote counts until the competition ends?

static holly
#

Hi how can i use easy-pil in py 3.11?

rugged shadow
#

user sends entry to bot, bot sends entry to channel

#

the entry in the channel will have some sort of vote btn

#

then the vote count will be handled by the bot

shrewd apex
idle dagger
#

thanks for the suggestions. i assume this needs to be coded? there is no existing solution for it?

vale wing
#

What advantages does it have

naive briar
#

I've done something like that

vale wing
#

I always use normal pillow and it seems easy enough

static holly
vale wing
#

Then just use normal pillow lol

#

Everything you can do in easy pil you can do in pillow

static holly
#

does the code stay the same between pillow and easy-pil?

vale wing
#

Cause that feels like a wrapper

static holly
#

I am looking to create a card for my level system

#

I haven't seen a tutorial for pillow, but there is one for esay pil

vale wing
static holly
#

can you share me the pics?

idle dagger
static holly
#
from easy_pil import Canvas, Editor, Font

user_data = {  # Most likely coming from database or calculation
    "name": "Shahriyar#9770",  # The user's name
    "xp": 1240,
    "next_level_xp": 5000,
    "level": 5,
    "percentage": 45,
}

background = Editor(Canvas((900, 300), color="#23272A"))
profile = Editor("assets/pfp.png").resize((150, 150)).circle_image()

# For profile to use users profile picture load it from url using the load_image/load_image_async function
# profile_image = load_image(str(ctx.author.avatar_url))
# profile = Editor(profile_image).resize((150, 150)).circle_image()

poppins = Font.poppins(size=40)
poppins_small = Font.poppins(size=30)

card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]

background.polygon(card_right_shape, "#2C2F33")
background.paste(profile, (30, 30))

background.rectangle((30, 220), width=650, height=40, fill="#494b4f", radius=20)
background.bar(
    (30, 220),
    max_width=650,
    height=40,
    percentage=user_data["percentage"],
    fill="#3db374",
    radius=20,
)
background.text((200, 40), user_data["name"], font=poppins, color="white")

background.rectangle((200, 100), width=350, height=2, fill="#17F3F6")
background.text(
    (200, 130),
    f"Level : {user_data['level']} "
    + f" XP : {user_data['xp']} / {user_data['next_level_xp']}",
    font=poppins_small,
    color="white",
)


background.show()
slate swan
#

easy-pil is just yet another dependency that isnt' really needed at all πŸšΆβ€β™‚οΈ basic pillow code it is

static holly
#

I would like to reproduce this card with pillow but I don't know this module at all...

slate swan
#

just read its docs

#

anyways, my question:
So basically there is a discord.File object which is a local image actually. And I want to get its link.
Like: when I click on the image (discord.File that i passed) inside embed, it opens up to a link.. so yea i want that link

#

please ping me if anyone can help me with this

slate swan
slate swan
#

i can screenshare if it's hard to get or if i'm not able to explain it right

slate swan
#

!d discord.Embed.image

unkempt canyonBOT
#

property image```
Returns an `EmbedProxy` denoting the image contents.

Possible attributes you can access are...
slate swan
#

i already tried that lol

#

doesn't work as per expectations

#

uhh, can ya hop in vc & look into problem?

#

sum issue?

slate swan
#

WWTF I CAN'T SCREENSHARE EVEN IN A SINGLE CHANNEL WTF

#

you can dm call

vale wing
slate swan
#

dear good afternoon. please tell me how to add a custom emoji to the description of the select menu? the usual discord emoji is added but the custom one is not

vale wing
#

@static holly this is from one of functions

vale wing
#

Are those constants scaring you or smth

#

Look at functions, not at constants, if you would want to have same thing in easy pil you would need to use them too, unless you put numbers straight in their places which can get confusing

#

And yeah there is a bad way of getting a pfp because I was dumb

static holly
#

all I want is to achieve this image...

slate swan
clear elm
#

error:

  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 64, in _suggestion
    message = await channel.send(embed=suggestEmbed)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/abc.py", line 1538, in send
    data = await state.http.send_message(channel.id, params=params)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').

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

Traceback (most recent call last):
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'suggestion' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.author.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').```
#

code:

@bot.tree.command(name="suggestion", description="Sends a suggestion to our suggestion channel!")
async def _suggestion(interaction, title:str, suggestion:str):
    channel = bot.get_channel(1059976520376012811)
    suggestEmbed = discord.Embed(color=0xFF5349)
    suggestEmbed.set_author(name=f'New suggestion by {interaction.user}', icon_url = f'{interaction.user.avatar}')
    suggestEmbed.add_field(name=f'Title: {title}', value=f'Suggestion: {suggestion}')

    message = await channel.send(embed=suggestEmbed)
  
    await message.add_reaction(':white_check_mark:')
    await message.add_reaction(':x:')

    channel = bot.get_channel(int(1059976520376012811))
    thread = await message.create_thread(
    name=f"{title} Discussion",
    reason="Suggestion")
  
    await thread.send("**Like, dislike or want to add onto someones suggestion?** Do that here! In this thread, you can discuss what you like, dislike or something smiliar you'd like to see!")
  
    embed=discord.Embed(title="Successful!", color=0x23B425)
    embed.add_field(name="This command was successful.", value="Your suggestion was successfully posted in #suggestions", inline=False)

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

You can use .display_avatar instead

#

!d discord.User.display_avatar

unkempt canyonBOT
#

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

For regular users this is just their default avatar or uploaded avatar.

New in version 2.0.
clear elm
#

thanks

#

no errors either

naive briar
#

It's just hard to notice 🐱

verbal hawk
#

How can I delete an already sent select menu within the callback?

naive briar
#

Send the code above it

#

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

clear elm
#

i changed it, same thing still happens

naive briar
#

Changed what

clear elm
#

the option values as strings to integers

naive briar
#

discord.py won't allow that, even if it does, it will convert it to string

#

Just change the thing you're trying to compare the option to strings

clear elm
#

ok

#

thanks, it works k_whiteheart

north kindle
#

how can i disable a button after its clicked?

clear elm
#

is it possible to make a bot react to a message that has a word in the setence, for example:
if i said welcome in a sentence
welcome to (server name)
welcome!
WeLCOme
it'd react to it (case insensitive)

clear elm
#
@bot.event
async def on_message(message):
  if message.author == bot.user:
    return
    
  if message.content == 'welcome':
    await message.add_reaction('πŸ‘‹')```
thin raft
#

if "welcome" in message.content.casefold()

clear elm
#
@bot.event
async def on_message(message):
  if message.author == bot.user:
    return
    
  if "welcome" in message.content.casefold()
    await message.add_reaction('πŸ‘‹')```?
thin raft
#

yeah

#

btw, instead of checking for bot.user check for message.author.bot

clear elm
#

is it possible to have multiple bot.events but all for different things. for example, on_member_join, on_command_error and on_message

naive briar
#

What

#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
teal glade
#

I'm having trouble checking whether or not a message contains ONLY emojis

thin raft
#

split the message at ":"

#

and go emoji by emoji checking it in the list

#

if all of them are true, it means its only emojis

#

or use

#

!d discord.Emoji

unkempt canyonBOT
#

class discord.Emoji```
Represents a custom emoji.

Depending on the way this object was created, some of the attributes can have a value of `None`...
naive briar
#

!d re.fullmatch

unkempt canyonBOT
#

re.fullmatch(pattern, string, flags=0)```
If the whole *string* matches the regular expression *pattern*, return a corresponding [match object](https://docs.python.org/3/library/re.html#match-objects). Return `None` if the string does not match the pattern; note that this is different from a zero-length match.

New in version 3.4.
naive briar
#

Why do you want only emojis anyway

clear elm
#
@bot.event
async def on_member_join(ctx, member):
  guild = bot.get_guild(1058181103132868619)
  channel = bot.get_channel(1058184521587105853)
  embed=discord.Embed(title=':sushi: WELCOME TO THE SERVER!', description=f'Hello, {member.mention}! Welcome to {guild.name}. Be sure to read #server-information and claim your roles in #reaction-roles!', color=0xFF5349)
  embed.add_field(name="It would also be greatly appreciated if you joined our group, the link is below!", value=":link: ", inline=False)
  
  await channel.send(embed=embed)

@bot.listen()
async def on_message(message):
  if message.author == message.author.bot:
    return
    
  if "welcome" in message.content.casefold():
    await message.add_reaction(':wave:')
  if "welc" in message.content.casefold():
    await message.add_reaction(':wave:')

@bot.listen()
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send(":k_exclaim: **__Error!__** Command not found! To view commands, use ``/help``.")

both the ones with bot.listen work but the welcome message doesn't

#

no errors

teal glade
thin raft
#

just do
if message.author.bot:

upbeat otter
thin raft
#

and then, remove the first if

upbeat otter
#

.bot returns a boolean value

#

no

thin raft
#

and?

#

if its a bot
return

#

idk what's wrong with that

upbeat otter
#

oh wait nvm I misunderstood, I didn't look at the code πŸ’€

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
#

https://paste.pythondiscord.com/eyewovixit
Error:

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 102, in mute
    time=convert(time)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 83, in convert
    unit = time[-1]
TypeError: 'NoneType' object is not subscriptable
naive briar
#

Read the error

#

The time argument is None

#

!e

None[-1]
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | <string>:1: SyntaxWarning: 'NoneType' object is not subscriptable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 |   File "<string>", line 1, in <module>
004 | TypeError: 'NoneType' object is not subscriptable
thin raft
#

send the command you used

slate swan
thin raft
#
@bot.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: nextcord.Member = None, time=None, *, reason=None):
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT role_id FROM mute WHERE guild = ?', (ctx.guild.id,))
            role_id = await cursor.fetchone()
            if role_id:
                muterole = ctx.guild.get_role(role_id[0])
    time=convert(time)```
#

time is predefined as None

#

if you call the command without time parameter

#

you will always get that error

slate swan
slate swan
thin raft
#

if you send code send it as text*

slate swan
slate swan
# thin raft send it as text
    if time == None:
        em2=nextcord.Embed(title="![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Error", description=f"![NoaX](https://cdn.discordapp.com/emojis/1071128440822059059.webp?size=128 "NoaX") Please set the time!", color=nextcord.Color.red())
        await ctx.send(embed=em2)        
        return```
thin raft
#

you haven't coded that up

thin raft
slate swan
#

Like did that first time=convert(time)

thin raft
#

yeah

gentle nova
#

Hey, create_voice_channel working, but why not working create_textchannel

thin raft
#

you used time before knowing its value

slate swan
# thin raft you used time before knowing its value
time=convert(time)
    if member == None:
        em1=nextcord.Embed(title=":NoaX: Error", description=f":NoaX: Please mention a member!", color=nextcord.Color.red())
        await ctx.send(embed=em1)
        return
    if time == None:
        em2=nextcord.Embed(title=":NoaX: Error", description=f":NoaX: Please set the time!", color=nextcord.Color.red())
        await ctx.send(embed=em2)        
        return
thin raft
#

or a better explanation

slate swan
#

i did look

thin raft
#

you did not

#

you need to CHECK IF TIME IS NONE and THEN use it

slate swan
#

IHB

#

ohhh

#

omg u r right

#

ty ill try

thin raft
#

take a rest

#

personal recommendation

gentle nova
#
created_voice_channels = await create_voice_channels(created_voice_channels) ---- This working
created_text_channels = await create_text_channels(created_text_channels) ---- This not
thin raft
#

send full code

gentle nova
#

okay solved this one πŸ˜„

thin raft
#

smh

gentle nova
#
TypeError: Client.run() got an unexpected keyword argument 'bot'``` any idea ?
#
client.run(token, bot=True)
young dagger
#

I wanted to know if this will run every 24 hours from the start time, regardless of how long it takes to update all the users, or if it will only update the users once every 24 hours after it completes updating all users?

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    users = await collection.find().to_list(length=None)
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier_and_rank = get_tier_and_rank(summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        await collection.update_one({"summoner_id": summoner_id}, {"$set": {"summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)```
young dagger
#

Will it wait for another 24 hours from the start time before beginning the next iteration of the loop?

static holly
#

hi, i have a xp and level system, all works but I would like the xp to reset to zero when the member levels up...
For example
at the end of level 3 > xp= 480/480
I want at the beginning of level 4 the member has > 0/750

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

        self.bot.loop.create_task(self.save())
        
        with open("level_system/users.json", "r") as f:
            self.users = json.load(f)
            
    def level_up(self, author_id):
        current_experience = self.users[author_id]["Experience"]
        current_level = self.users[author_id]["Level"]
        
        if current_experience >= math.ceil((6 * (current_level ** 4)) / 2.5):
            self.users[author_id]["Level"] += 1
            
            return True
        else:
            return False
    
    async def save(self):
        await self.bot.wait_until_ready()
        while not self.bot.is_closed():
            with open("level_system/users.json", "w") as f:
                json.dump(self.users, f, indent=4)
                
            await asyncio.sleep(5)
naive briar
naive briar
#

And JSON isn't a database

young dagger
static holly
naive briar
#

Set the experience to 0?

young dagger
static holly
naive briar
#

It will wait until the next 24 hours

static holly
naive briar
gentle nova
#

its possible to make bot change server icon every day ?

naive briar
slate swan
#

!d discord.Guild.edit

unkempt canyonBOT
#
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the guild.

You must have [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") to edit the guild.

Changed in version 1.4: The `rules_channel` and `public_updates_channel` keyword parameters were added.

Changed in version 2.0: The `discovery_splash` and `community` keyword parameters were added.

Changed in version 2.0: The newly updated guild is returned...
slate swan
#

icon kwarg

gentle nova
#

await edit(icon="link") ?

young dagger
gentle nova
#
@client.command()
@commands.is_owner()
async def stop(ctx):
    await ctx.send('Shutting down')
    await client.logout()
    print (Fore.GREEN + f"{client.user.name} PasijungΔ—." + Fore.RESET)

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'logout'

naive briar
#

Where did you get that method from

gentle nova
#

google

#

Im doing another thing , so using ctx not interaction

naive briar
#

Then Google is not very correct then

#

!d discord.Client.close

unkempt canyonBOT
#

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

Closes the connection to Discord.
gentle nova
#

now close is not defined

naive briar
#

Show the code then

gentle nova
#
@client.command()
@commands.is_owner()
async def stop(ctx):
    await ctx.send('Shutting down')
    await close()
    print (Fore.GREEN + f"{client.user.name} PasijungΔ—." + Fore.RESET)
slate swan
naive briar
#

close is a method of Client object, did you even read what I sent

slate swan
#

but idj how to tbh i tried that

gentle nova
#

so should i do client.close() ?

#

yay

#

thank you πŸ˜„

#

@slate swani newbie, but i think so you need make guild reading

slate swan
#

wdym

gentle nova
#

i understand now that one person can change all guilds language right ?

slate swan
#

No

gentle nova
#

then do checks

wide bay
#

!d discord.Client.close

slate swan
gentle nova
#

@naive briarThis guy can help you

wide bay
#

I'm a beginner joe_salute

sturdy shadow
naive umbra
gentle nova
#
 await guild.edit(icon='link')

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'guild' where it is not associated with a value

naive umbra
# naive umbra what's the problem?

the idea here is that you store the preferred language to a specific guild in your database, each time your bot responds you should check what that preferred language is for the guild the command got dispatched in and translate the text to it before making the response, what problem have you encountered on the way of this?

naive umbra
slate swan
gentle nova
#

@naive umbraThere is no rest of code, im trying to make only change server icon once per day , so i need findout how to make it to change atleast once

naive umbra
#

where is guild defined?

naive umbra
#

like, which part exactly

slate swan
naive umbra
#

wdym with choosing which language?

gentle nova
#

@naive umbraI need to know if command line is close or not, and how to put link to read

slate swan
#
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language != "hebrew" or "english":
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    role = await cursor.fetchone()
                    if role:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', ( ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (role_id, guild) VALUES (?, ?)', ( ctx.guild.id,))
                await ctx.send(f"Successfuly set the helpme language to - {language}")
                await db.commit()```
#

snt like that

naive umbra
naive umbra