#discord-bots

1 messages · Page 965 of 1

slate swan
#

above the on_message function ( or any event)

formal basin
#

I replaced it with my on_message

slate swan
#

cool, recheck if you really did that.

#

Lol

#
  1. listen is only be used with commands.Bot
  2. you can have multiple listeners but only one event ( of same kind)
  3. there are multiple ways to do an listener
#

never used on_message before tbh 🤷

formal basin
#

Oh

formal basin
slate swan
#

I've used on_message_delete

formal basin
slate swan
#

🏃‍♂️ i use MessageCreateEvent

slate swan
formal basin
#

What does a snipe command do?

slate swan
#

how can i make a command only to be used in a particular guild?

slate swan
slate swan
slate swan
#

k ty

blissful sparrow
#

Ok so I've added the following:

@bot.command()
async def ping(ctx):
    await ctx.send(f'The bot\'s latency is {round(bot.latency * 1000)}ms')

but the bot won't reply, any idea why?

slate swan
#

can I see all of the code.

#

make sure its above bot.run()

blissful sparrow
#
import discord
from discord.ext import commands

import requests
import json

token = 'token'
intents = discord.Intents(messages=True, guilds=True)


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


@bot.event
async def on_ready():
    print('The {0.user} bot has logged in!'.format(bot))

@bot.command()
async def ping(ctx):
    await ctx.send(f'The bot\'s latency is {round(bot.latency * 1000)}ms')

bot.run(token)
slate swan
#

@bot.command needs ()

#

.command always needs the parentheses

blissful sparrow
#

ye i just removed that to see if that was the problem but it still has the problem even with parenthesis

slate swan
#

I suggest using time btw

formal basin
#

I still can’t figure this out

blissful sparrow
#

bot.time?

slate swan
#
@client.command(pass_context=True)
async def ping(ctx):
    """**Pong!**"""
    before = time.monotonic()
    message = await ctx.send("Pong!")
    ping = (time.monotonic() - before) * 1000
    await message.edit(content=f"Pong!  `{int(ping)}ms`")
    print(f'Ping {int(ping)}ms')

@blissful sparrow using time package you can do this for ping.

formal basin
#

What is bot.time?

slate swan
#

just make sure to add import time to the very top of your code @blissful sparrow

formal basin
blissful sparrow
formal basin
blissful sparrow
blissful sparrow
#

yup

slate swan
#

let me see all of your code again

blissful sparrow
#
import discord
from discord.ext import commands
import time

import requests
import json

token = 'token'
intents = discord.Intents(messages=True, guilds=True)


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


@bot.event
async def on_ready():
    print('The {0.user} bot has logged in!'.format(bot))

@bot.command(pass_context=True)
async def ping(ctx):
    """**Pong!**"""
    before = time.monotonic()
    message = await ctx.send("Pong!")
    ping = (time.monotonic() - before) * 1000
    await message.edit(content=f"Pong!  `{int(ping)}ms`")
    print(f'Ping {int(ping)}ms')
 )

bot.run(token)
slate swan
#

ok remove what I told you to add

blissful sparrow
#

done

slate swan
#
@bot.command()
async def ping(ctx):
    await ctx.send(f'Pong {bot.latency}!')

try this instead,

formal basin
blissful sparrow
#

Still refuses to reply :/

slate swan
#

is there a documentation for buttons on d.py docs?
if yes may i have the link?

blissful sparrow
#

local as of rn

slate swan
slate swan
slate swan
blissful sparrow
#

ive been at it for a while and idk why its not replying

blissful sparrow
#

it has admin perms and message intents

formal basin
unkempt canyonBOT
#

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

New in version 2.0.
slate swan
#

click on the blue text

#

ty

formal basin
#

@bot.command()
@commands.has_permissions(manage_roles=True)
async def welcome_setup(ctx, channel: discord.TextChannel, *, message):

    with open('welcome.json') as f: data = json.load(f)
    data[str(ctx.guild.id)] = {}
    data[str(ctx.guild.id)]['channel_name'] = channel.name
    data[str(ctx.guild.id)]['channel_id'] = channel.id
    data[str(ctx.guild.id)]['message'] = message
  
    with open('welcome.json', 'w') as f:
        json.dump(data, f)
    await ctx.send("welcome channel setup")


async def on_member_join(member):

  with open('welcome.json') as welcome_file:
    data = json.load(welcome_file)
    channel = data[str(member.guild.id)]["channel_id"]
    channel = member.guild.get_channel(channel)
    message = data[str(member.guild.id)]["message"]
    

    await channel.send(f"{message}")

Guys why isn’t this working

I’ve dumped the message into the json file

slate swan
#

@blissful sparrow

@bot.command()
async def exx(ctx):
   await ctx.send("Sent message!")

try this for testing purposes

#

just do your command prefix then exx

blissful sparrow
slate swan
#

what editor are you using, or ide?

blissful sparrow
#

VSC

slate swan
blissful sparrow
#

yup

slate swan
#

what python version do you have?

blissful sparrow
umbral night
#

isnt dpy discontinued

blissful sparrow
#

erm sec

slate swan
umbral night
#

i thought they stopped working on it

vale wing
#

It is recontinued

umbral night
#

OH

unkempt canyonBOT
#
Naw.

No documentation found for the requested symbol.

umbral night
#

YES

vale wing
#

Danny is back

#

Like 1 month ago

heavy folio
#

what the

umbral night
blissful sparrow
#

3.10.2

formal basin
#

@bot.command()
@commands.has_permissions(manage_roles=True)
async def welcome_setup(ctx, channel: discord.TextChannel, *, message):

    with open('welcome.json') as f: data = json.load(f)
    data[str(ctx.guild.id)] = {}
    data[str(ctx.guild.id)]['channel_name'] = channel.name
    data[str(ctx.guild.id)]['channel_id'] = channel.id
    data[str(ctx.guild.id)]['message'] = message
  
    with open('welcome.json', 'w') as f:
        json.dump(data, f)
    await ctx.send("welcome channel setup")


async def on_member_join(member):

  with open('welcome.json') as welcome_file:
    data = json.load(welcome_file)
    channel = data[str(member.guild.id)]["channel_id"]
    channel = member.guild.get_channel(channel)
    message = data[str(member.guild.id)]["message"]
    

    await channel.send(f"{message}")

Guys why isn’t this working

I’ve dumped the message into the json file

vale wing
#

Oh heck json again

umbral night
#

im looking for some $20 optiplex i can host my bots on

vale wing
#

Also do you have error handlers

formal basin
# vale wing Show your JSON file and tell me if you are getting any errors

{"channel_name": "testing", "channel_id": 946000818891526144, "879646357940473866": {"channel_name": "discord-server-bot", "channel_id": 879658500312170496, "message": " joined the server"}, "942442967174623322": {"channel_name": "testing", "channel_id": 946000818891526144}, "856209570384707635": {"channel_name": "welcome", "channel_id": 868148492638490664}, "919206575841869865": {"channel_name": "general", "channel_id": 919206575841869868}}

slate swan
#

@blissful sparrow try using a different editor, I recommend Thonny

umbral night
#

do yall prefer dpy over djs

formal basin
vale wing
#

Do you have

else:
    raise error``` at them?
formal basin
vale wing
#

Handlers

formal basin
slate swan
#

@blissful sparrow py -3.10.2 -m pip install discord.py

#

try this in cmd

formal basin
#

For my error handle

vale wing
#

Do you have only one error handler or many

#

Like global/local

blissful sparrow
formal basin
formal basin
vale wing
#

It should be at every error handler I think

formal basin
vale wing
vale wing
#

1 handler?

formal basin
vale wing
#

Ig you get no errors because of improper error handlers

formal basin
#

This is what I mean

vale wing
#

All the inner bodies should look like this

if isinstance(error, ErrorClass1):
    ...
elif isintance(error, ErrorClass2):
    ...

...
else:
    raise error```
#

Including locals

formal basin
#

What’s a global handler

vale wing
#

Idk about locals much but you should try to raise the error in them

vale wing
#

The locals are @command.error

formal basin
#

I’m using both

vale wing
formal basin
#

I’m going to change that

#

Ok done

vale wing
#

@formal basin try adding simple raise error in those local error handlers

vale wing
#

To see if there are errors

#

And what kind of errors

formal basin
#

What do I do?

vale wing
#

You can remove it later

slate swan
#
@client.command()
async def test1(ctx):
  button1 = Button(label="click me", style=discord.ButtonStyle.green, emoji="😀")
  button2 = Button(label="Hello!", style=discord.ButtonStyle.green, emoji="😀")
  button3 = Button(label="Hi", style=discord.ButtonStyle.green, emoji="😀")
  button4 = Button(label="test", style=discord.ButtonStyle.green, emoji="😀")
  view = View()
  view.add_item(button1)
  view.add_item(button2)
  view.add_item(button3)
  view.add_item(button4)
  await ctx.send(f"Hello!", view=view)

i used this code and started the bot
no errors were there in console but the command is unresponsive

vale wing
#

You may also comment them out

#

Your current objective is to find where the program stops working

vale wing
#

Why not subclass the view

formal basin
#

So

@command.error
async def command_error(ctx, error):
raise error

await ctx.send*(“message”)

vale wing
#

I don't see anything wrong with that anyways

#

@formal basin forget it just comment out the local handlers

vale wing
#

Select them and CTRL + /

formal basin
#

I’m not on computer

vale wing
#

Understandable

formal basin
#

So how can I do it

vale wing
#

Then go with raising

formal basin
#

So

@command.error
async def command_error(ctx, error):
raise error

await ctx.send*(“message”)

vale wing
#

Remove it at all

#

Cause none of code gets executed after error is raised

formal basin
#

All of the local errors

formal basin
vale wing
#

Eh wait we are working with event sorry for that

vale wing
#

In on_member_join print channel

formal basin
#

print(channel)

vale wing
#

Yes

formal basin
#

Ok

#

Done

vale wing
#

What did you get

formal basin
#

You want me to run test it?

vale wing
#

Yeah

formal basin
#

Ok 1 sec

formal basin
#

Uh oh

#

Hold on

slate swan
# vale wing Why not subclass the view
class MyView(View):
  @discord.ui.button(label="click here", style=discord.ButtonStyle.green, emoji=":emark:")
  async def button_callback(self, button, interaction):
    await interaction.response.send_message("hello")

@client.command()
async def test1(ctx):
  view = MyView()
  await ctx.send("Hi!", view=view)

still no errors and command unresponsive

formal basin
#

@vale wing it printed nothing

formal basin
#

@vale wing I fixed it

heavy folio
#

do you have message_content intents?

slate swan
formal basin
#

The problem was I didn’t have @bot.event

heavy folio
#

Why does my bot doesn't respond to commands in v2.0? / Why is message.content not there.
Discord.py v2.0 has migrated to api v10, and with this has come the introduction of Intents.message_content, which is disabled by default.
This means that you will need to __explicitly enable it in code and in the panel, at https://discord.com/developers/applications

intents = discord.Intents.default()  # All but the THREE privileged ones
intents.message_content = True  # Subscribe to the Message Content intent
bot = commands.Bot(command_prefix='-', intents=intents)  # Pass the intents into your commands.Bot or discord.Client
``` NOTE: Still not responding to commands? see `?faq on_message` in #playground
slate swan
#

k

formal basin
#

@vale wing I have a new problem

#

I want to do like ?welcome_setup #welcome {member.mention} joined the server

heavy folio
#

did you update to 2.0
pip install git+https://github.com/Rapptz/discord.py

formal basin
#

But it doesn’t mention the user

slate swan
#

is there a way to read a text file in a specified format?
like this:

user#0001 5 10 30
#

so it would read user#0001 as the author, 5 as test1, 10 as test2, 30 as test3, and then i could do a if statement like this:

if test1 >= 6
lofty tinsel
#

is it possible to leave a blank field in an embed. for example the description or the name of the field?

slate swan
heavy folio
slate swan
slate swan
#

itll be added there once andthen itl be there

slate swan
lofty tinsel
#

Nah

#

That's not work

lofty tinsel
lofty tinsel
#

I'll try with use an invis char
\u2800

slate swan
#

Nvm idk actually

slate swan
paper sluice
#

u need to have dpy 2.0 to use view

#

so pip install git+https://github.com/Rapptz/discord.py to install it

formal basin
#

What does this error mean?

paper sluice
slate swan
formal basin
#

Nope

slate swan
paper sluice
#

no wait ur missing a comma @formal basin

paper sluice
slate swan
paper sluice
slate swan
slate swan
paper sluice
formal basin
#

Oh

slate swan
#
data['test1']

like that

#

you can of course, use lists in place of a single value

#

or a whole new dictionary

#

i don wanna do a dictionary

slate swan
#

havent done anything yet, i was asking so i could start on it

slate swan
slate swan
paper sluice
slate swan
slate swan
#

id need to search for the ctx.authors data

#

so if the ctx.author is user2#0001 then it reads all the data for user2#0001

slate swan
slate swan
#

something like this?

#
import json
def read_data("filename.json") as f:
  data = json.load(f)
  data[f'{ctx.author}']
  if test1 >= 5:
    ...
spring flax
#

for voice-text channel linking, would changing channel permissions each join be bad on ratelimits?

cold oyster
#

Uhh, Guys is it on_member_join or on_member_joined...?

cold oyster
#

Ok

#

Ty

cold oyster
slate swan
cold oyster
slate swan
#
async def on_member_join(member):
    channel = bot.get_channel(welcomechannelid)
    await channel.send("welcome")
cold oyster
#

No ctx?

slate swan
#

oh yea

cold oyster
#

xd

slate swan
#

think u cant use ctx lol

cold oyster
#

Btw thank you

slate swan
#

that shold work, i edited it

#

you also need to enable member intents in the code, dev portal and also import intents

cold oyster
#
@client.event
async def on_member_join(member):
  channel = (channe_id)
  await channel.send("hemlo")
#

What about dis?

slate swan
#

no, that wont work

cold oyster
#

oh

slate swan
#

you have to use get_channel

#

look at my edited code

cold oyster
#

ook

slate swan
#

pretty sure this wont work if ur bot is public cause people join other servers and you cant welcome other server members in ur server xd

slate swan
#

if ur bot is for your server only then youre good to go with that

cold oyster
#

Ye its only my server

slate swan
#

!d intents

unkempt canyonBOT
#
cold oyster
#

a

#

1 que

#

Wot

slate swan
#

dawg idk how this thing works

#

look at the member intents

livid jacinth
#

Hey, i have an error in my giveaway command but i dont know how to fix it ```py
@bot.command(name="giveaway")
@commands.has_permissions(administrator=True)
async def giveaway(ctx, mins : int, , prize: str):
user=ctx.author
end = datetime.datetime.utcnow() + datetime.timedelta(seconds= mins
60)
embed = discord.Embed( title = "Giveaway", description = f"Host: {user}\nPrize: {prize}", color=discord.Color.gold())
embed.add_field(name= "Ends at:", value=f"{end} (in {mins}min)")

gwmsg = await ctx.send(embed = embed)
await gwmsg.add_reaction("🎉")

await asyncio.sleep(mins)
gwmsg1 = await ctx.channel.fetch_message(gwmsg.id)    
users = await gwmsg1.reactions[0].users().flatten()
users.pop(users.index(bot.user))
winner = random.choice(users)
await ctx.send(f"{winner.mention} hat {prize} gewonnen!")```
#

Thats the error: ```Ignoring exception in command giveaway:
Traceback (most recent call last):
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\tim10\OneDrive\Desktop\Testbebo\bot - Kopie.py", line 88, in giveaway
winner = random.choice(users)
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\random.py", line 347, in choice
return seq[self._randbelow(len(seq))]
IndexError: list index out of range

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

Traceback (most recent call last):
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\tim10\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range```

slate swan
livid jacinth
slate swan
livid jacinth
#

bc this py end = datetime.datetime.utcnow() + datetime.timedelta(seconds= mins*60) dont working

slate swan
#

huh

#

is that even valid, idk im bad with adding dt objects

spring flax
# slate swan elaborate

when you join a VC, you set access to a text channel. Should this be done with giving a role or changing channel perms

spring flax
#

but is the permission changing bad?

slate swan
#

I'd choose a role tbh

livid jacinth
#

Hey how can i convert the time mins? ```py
@bot.command(name="giveaway")
@commands.has_permissions(administrator=True)
async def giveaway(ctx, mins : int, , prize: str):
user=ctx.author
end = datetime.datetime.utcnow() + datetime.timedelta(seconds= mins
60)
embed = discord.Embed( title = "Giveaway", description = f"Host: {user}\nPrize: {prize}", color=discord.Color.gold())
embed.add_field(name= "Ends at:", value=f"{end} (in {mins} min)")

gwmsg = await ctx.send(embed = embed)
await gwmsg.add_reaction("🎉")

await asyncio.sleep(mins)
gwmsg1 = await ctx.channel.fetch_message(gwmsg.id)    
users = await gwmsg1.reactions[0].users().flatten()
users.pop(users.index(ctx.guild.me))
winner = random.choice(users)
await ctx.send(f"{winner.mention} hat {prize} gewonnen!")
slate swan
#

who can add to my bot that every message gets logged, can pay

livid jacinth
#

I dont know how can i set the timestamp to the end of the giveaway

valid snow
#

hello, how do you do during an embed to make a footer with the time that the command took to execute. if it is a command that takes time for example put a footer saying 30s

#

I know how to make a timestamp but not this

livid jacinth
#

And how can i do that?

valid snow
#

yes a footer to say how long the command took to get a response from the bot

paper sluice
valid snow
#

I'm not english so i dont understand everything u said

unkempt canyonBOT
#

property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.

This could be referred to as the Discord WebSocket protocol latency.
valid snow
#

Just as a footer

paper sluice
#

nah i think they want to time a command, not bot

valid snow
#

Yes

unkempt canyonBOT
#

time.perf_counter() → float```
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.

Use [`perf_counter_ns()`](https://docs.python.org/3/library/time.html#time.perf_counter_ns "time.perf_counter_ns") to avoid the precision loss caused by the [`float`](https://docs.python.org/3/library/functions.html#float "float") type.

New in version 3.3.

Changed in version 3.10: On Windows, the function is now system-wide.
paper sluice
#

ok im gonna write some rough code but u can do this

async def func(...):
    start = time.perf_counter()
    ...
    embed = discord.Embed(...)
    end = time.perf_counter
    embed.set_footer(text=end-start)
    await ctx.send(embed=embed)
#

u can change the position of end, if u want to it to include the time took to create embed to put it above embed = discord...

valid snow
#

Okay i'll try

green bluff
#

Hey guys so what does adding await do to an event
/ function

#

do

paper sluice
#

or use use a contextmanager-time function, if u know how they work

paper sluice
#

now what are you trying to do?

green bluff
#

or does it do all at the same itme

paper sluice
#
await foo()

this will only wait for foo to finish its task

green bluff
#

what if

#

do


await foo()
await foo2()
#

@paper sluice would that do both at once or will it wait for foo to finish then do foo2

paper sluice
#

first it will wait for foo then it will wait for foo2

sterile talon
#

hello

#

im trying to make a fivem bot. i secess all exept the discord tag.
look at the code

sterile talon
slate swan
#

await lets you run the rest of the code while in case if one function takes time to execute

#

your other code still works perfectly fine

#

thats what awaiting is

paper sluice
#

!e

from asyncio import run, sleep

async def foo():
    print('entered foo')
    await sleep(1)
    print('still in foo')
    return 1


async def bar():
    print('entered bar')
    await sleep(1)
    print('still in bar')
    return 1


async def main():
    print('entered')
    await foo()
    await bar()
    print('left')
    
run(main())

this is what i mean

unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

001 | entered
002 | entered foo
003 | still in foo
004 | entered bar
005 | still in bar
006 | left
paper sluice
#

it first waits for foo to finish, even when foo is sleeping, it still waits for it

sterile talon
#
if len(resp) > 25:
        for i in range(round(len(resp) / 25)):
            embed = discord.Embed(title='FiveMBot Bot', description='Server Players', color=discord.Color.blurple())
            embed.set_footer(text=f'Total Players : {total_players} | FiveMBot | {timenow}')
            count = 0
            for player in resp:
                embed.add_field(name=f"{player['name']}ID : {str(player['id'])}{str(player['discord'])} ",value="----------", inline=False)
                resp.remove(player)
                count += 1
                if count == 25:
                    break
                else:
                    continue
      
            #await channel.send(embed=embed)
            message= await channel.fetch_message(962264818520297512)
            await message.edit(embed=embed)
            
    else:
        embed = discord.Embed(title='FiveMBot Bot', description='Server Players', color=discord.Color.blurple())
        embed.set_footer(text=f'Players : {total_players} |  {timenow}')
        for player in resp:

          embed.add_field(name=f"{player['name']} ID : {str(player['id'])} {str(player['discord'])}",value="----------", inline=False)
paper sluice
#

if i used something like gather the output would be

entered
entered foo
entered bar
still in foo
still in bar
left

sterile talon
#

?

paper sluice
#

@sterile talon explain your problem

sterile talon
#

oh lol

#

its dosent work

#

the discord tag

sterile talon
#

at the json its look like this (the discord)

lofty tinsel
#
@client.group(invoke_without_command=True)
async def help(ctx):
    start = time.perf_counter()
    end = time.perf_counter
    em=discord.Embed(title = "**📂 | __Commands List__**\n\u2800", color=0x2F54C7)

    em.add_field(name = "📒 | Acc Related Command", value = "**>randomkc** ➛ Generate a random KeyChain\n>**lockedacc** ➛ Get a Locked Account ( No-Bot )\n>**creation** ➛ Get estimated creation date of a tag\n>**acc** ➛ Get Account’s Infos\n>**clan** ➛ Get Clan’s Infos\n>**appledevs** ➛ Get Apple Devices for a specific year\n**samsungdevs** ➛ Get Apple Devices for a specific year\n**device** ➛ Get help to find device's account ( mention Local + Year )\n\u2800", inline = False)
    em.add_field(name = "#️⃣ | Tag Related Command", value = "**>3gen** ➛ Generate a random 3 digit tag\n>**4gen** ➛ Generate a random 4 digit tag\n>**7gen** ➛ Generate a random 7 digit tag\n>**taggen** ➛ Generate a random 6 digit tag\n>**clangen** ➛ Generate a random 4/5/6 digit clan tag", inline = False)
    em.set_footer(text= f"command successfully completed !" (end-start))

    await ctx.send(embed = em)
paper sluice
#
    end = time.perf_counter

forgot to call this

lofty tinsel
#

bt i have this error Command raised an exception: TypeError: unsupported operand type(s) for -: 'builtin_function_or_method' and 'float'

paper sluice
#

it should be end = time.perf_counter()

sterile talon
#

"discord:739178267361148950"

#

and the others like the name look like this

#

"name":"Broxax"

#

@paper sluice

paper sluice
#
    em.set_footer(text= f"command successfully completed !" + str(end-start))

and this

#

what are you expecting @sterile talon

sterile talon
#

to take like the others and put it on the embed for eatch player

lofty tinsel
maiden fable
#

There's an unclosed bracket in former lines

lofty tinsel
#

Yes why?

#

how Can i close it

maiden fable
#

Adding a ) at the required place

paper sluice
lofty tinsel
paper sluice
#

these are not supposed to be together

lofty tinsel
paper sluice
#
@client.group(invoke_without_command=True)
async def help(ctx):
    start = time.perf_counter()
    em = discord.Embed(title="**📂 | __Commands List__**\n\u2800", color=0x2F54C7)
    
    em.add_field(name="📒 | Acc Related Command", value="**>randomkc** ➛ Generate a random KeyChain\n>**lockedacc** ➛ Get a Locked Account ( No-Bot )\n>**creation** ➛ Get estimated creation date of a tag\n>**acc** ➛ Get Account’s Infos\n>**clan** ➛ Get Clan’s Infos\n>**appledevs** ➛ Get Apple Devices for a specific year\n**samsungdevs** ➛ Get Apple Devices for a specific year\n**device** ➛ Get help to find device's account ( mention Local + Year )\n\u2800", inline=False)
    em.add_field(name="#️⃣ | Tag Related Command", value="**>3gen** ➛ Generate a random 3 digit tag\n>**4gen** ➛ Generate a random 4 digit tag\n>**7gen** ➛ Generate a random 7 digit tag\n>**taggen** ➛ Generate a random 6 digit tag\n>**clangen** ➛ Generate a random 4/5/6 digit clan tag", inline=False)
    end = time.perf_counter()
    em.set_footer(text=f"command successfully completed !" + str(end - start))
    
    await ctx.send(embed=em)

this will time the amount of time it took to create embed

errant fossil
#

'AttributeError: 'Client' object has no attribute 'load_extension'' I'm trying to load a cog but I get this

unkempt canyonBOT
lofty tinsel
#

still doesn't work ryuga

#

heroku

#

eheberg

tacit scaffold
#

!hosting

lofty tinsel
#

why this error?

#

Nah

#

Ahh okay

#

client.remove_command("help")

#

i need that

granite parcel
#

||patron_low ||

lofty tinsel
#

wojtazon do you know how to add a footer to my embed to tell how long the command took to run. The time between the >help and the response of the bot

slate swan
#

use the datetime module and subtract datetime.datetime.now() from ctx.message.created_at

tacit scaffold
#

!d discord.TextChannel.topic

#

None

#
var http = require('http'); http.createServer(function (req, res) { res.write("I'm alive"); res.end(); }).listen(8080);
lofty tinsel
#

why there is time difference I put utc.now

vale wing
#

I guess you need to add another timezone

lofty tinsel
#

At worst it doesn't matter I leave it like that for now

#

I'm stuck on a command

#

Can i tell u what i want to do and if u know Can u help me?

boreal ravine
#

sure

green bluff
#

why cant my loop

#

use self

boreal ravine
green bluff
#

no like

#

if i dont pass an arguement i get the error below

lofty tinsel
# boreal ravine sure

I would like to make a command that gives the approximate date of creation of an account. The creation date depends on the tag (#) of the player and it is with the help of this list that the bot will give the creation date. The creation date depends on the number of letters in the tag and the first letter.
The list is this: ```6 digit tag = august-october 2012

#UXXXXX = august 2012
#UXXXXXX/#2XXXXXX/#LXXXXXX = december 2012

#XXXXXXX = 2013

#Qxxxxxxx = end 2013
#Gxxxxxxx = start/early 2013
#Rxxxxxxx = summer 2013
#Vxxxxxxx = 2014
#Pxxxxxxx = start-early 2014
#9xxxxxxx = early 2014

#2xxxxxxxx = early-end 2015
#8xxxxxxxx = start-early 2015
#9xxxxxxxx = 2016
#Pxxxxxxxx = end 2016
#Yxxxxxxxx = end 2017
#Lxxxxxxxx = end 2018
#Qxxxxxxx = end 2020


and the person will make the command >creation #TAGPLAYER and the bot will adapt its answer to the number of letters in the tag and its first letter
green bluff
#

and u could use strftime to format it nicely

lofty tinsel
#

Its not for discord creation date

#

For a game

green bluff
#

then why tf r u asking here

lofty tinsel
#

because i'll do the command with my bot lmao

green bluff
lofty tinsel
#

damn u dont understand

lofty tinsel
#

nvm

green bluff
#

like it cant be done?

lofty tinsel
#

I just need the main idea and then I make the script

boreal ravine
green bluff
#

its just that self is not defined when i input it

livid jacinth
#

Hey why is this doesnt working ```py
embed = discord.Embed( title = "Giveaway", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())

boreal ravine
green bluff
livid jacinth
boreal ravine
livid jacinth
slate swan
#

how to unban member by using both id and username

green bluff
boreal ravine
#

it's a method

#

use self to access it

green bluff
boreal ravine
# green bluff ?
class A:
    def foo(*args, **kwargs):
        ...

    def bar():
        self.foo(...)
``` you access it by using `self`
slate swan
#

how to unban member by using both id and username

boreal ravine
livid jacinth
#

Hey why is this doesnt working ```py
embed = discord.Embed( title = "Giveaway", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())

livid jacinth
#

I dont know how to set the Timestamp to the time when the Giveaway ends

boreal ravine
# green bluff ?

the code earlier was already correct, you just had to access it using self

green bluff
boreal ravine
#

yes

slate swan
#

how to unban member by using both id and username

boreal ravine
boreal ravine
slate swan
#

no one replied

green bluff
livid jacinth
#

Hey I dont know how to set the Timestamp to the time when the Giveaway ends ```py
embed = discord.Embed( title = "Giveaway", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())

boreal ravine
# green bluff

put the second start method inside the class's initializer and remove the first one

boreal ravine
livid jacinth
# boreal ravine what's `time`
@bot.command(name="giveaway")
@commands.has_permissions(administrator=True)
async def giveaway(ctx, time: str, *, prize: str):
    time = convert(time)
    user=ctx.author
    endtime = datetime.datetime.utcnow() + datetime.timedelta(time)

    if not prize or time == 0:
        return

    embed = discord.Embed( title = "**Giveaway**", timestamp = datetime.datetime.utcnow() + datetime.timedelta(time), color=discord.Color.gold())


    embed.add_field(name= "Host:", value=f"{user}")

    embed.add_field(name='** **', value='** **', inline=True)
    embed.add_field(name='** **', value='** **', inline=True)

    embed.add_field(name="Prize:", value=f"{prize}")

    gwmsg = await ctx.send(embed = embed)
    await gwmsg.add_reaction("🎉")

    await asyncio.sleep(int(time))
    gwmsg1 = await ctx.channel.fetch_message(gwmsg.id)    
    users = await gwmsg1.reactions[0].users().flatten()
    users.pop(users.index(ctx.guild.me))
    winner = random.choice(users)
    await ctx.send(f"{winner.mention} hat {prize} gewonnen!")
slate swan
#

like sometime id and sometime username

boreal ravine
#

Use a try-except ig

green bluff
#

the self.verification loop should be awaited

#

could i make it asynchronous

green bluff
#

and also the only reason it has to be async is cause im using dpy 2.0

boreal ravine
green bluff
#

that worked!

boreal ravine
#

👍

green bluff
boreal ravine
#

Use get_member/fetch_member

green bluff
#

discord.utils.get(self.client.guild.members, id=id)?

green bluff
lofty tinsel
#

I'm working with API and i need json. How to pip install json?

slate swan
#

you don't need to install json it's a standard library

slate swan
#

*module

livid jacinth
#

Hey, how can i set an error if an argument is missing in a command?

slate swan
cold sonnet
#

and it ain't even a deco

slate swan
cold sonnet
#

and don't make the argument optional

slate swan
#

just use run_in_executor while using the library

#

!d asyncio.loop.run_in_executor

unkempt canyonBOT
#

awaitable loop.run_in_executor(executor, func, *args)```
Arrange for *func* to be called in the specified executor.

The *executor* argument should be an [`concurrent.futures.Executor`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Executor "concurrent.futures.Executor") instance. The default executor is used if *executor* is `None`.

Example:
slate swan
#

basically, use a blocking function, without the function blocking your code

boreal ravine
#
loop = asyncio.get_event_loop()
loop.run_in_executor(None, bot.run, token)
lofty tinsel
slate swan
lofty tinsel
# slate swan didnt understand what you meant

I want to do a command >creation + #PLAYERTAG which will give the date of creation of the # according to the length of the tag and its first letter.
Let's say I do >creation #UVGP22 then the bot will print "account created between August and October" because according to the list above the tag has a length of 6 letters and begins with the letter U

lofty tinsel
#

if / else?

slate swan
#
tag = member_tag

if len(tag) == 6 and tag.startswith("#U"):
        '''created between whatever month'''
#

smth like this

lofty tinsel
#

ok but the tag depend what the guys enter

#

the guy will do >creation #UXXXX

slate swan
#

yeah

lofty tinsel
#

and the bot need to understand what he asked to reply

#

How Can i do that

slate swan
#
async def creation(ctx: commands.Context, tag: str):
      ...

''' USAGE '''
>creation #UFFFF667

here in the function, tag will be set to #UFFFF667```
lofty tinsel
#
@client.command()
async def creation(ctx: commands.Context, tag: str):
    tag = int(input())

    if len(tag) == 6 and tag.startswith("#U","#V","#C","#P","#2","#8","#9","#0","#O"):
        await ctx.send("created between whatever month")
#

nothing happen

hushed galleon
#

you're using input() in your command which is halting the bot's execution to wait for an integer from the console

#

!d str.startswith < also it only takes a single string or tuple of strings, not 9 strings

unkempt canyonBOT
#

str.startswith(prefix[, start[, end]])```
Return `True` if string starts with the *prefix*, otherwise return `False`. *prefix* can also be a tuple of prefixes to look for. With optional *start*, test string beginning at that position. With optional *end*, stop comparing string at that position.
lofty tinsel
#

But in fact I want a guy to do >creation in the discord discord server

lofty tinsel
hushed galleon
#

you already did so by writing a tag parameter

#

dpy will try to match the user's message to the parameters of your function

lofty tinsel
#
@client.command()
async def creation(ctx: commands.Context, tag: str):
    tag = #depend the guy entered

    if len(tag) == 6 and tag.startswith("#U"):
        await ctx.send("created between august-october")
#

how to take the information that the guy entered?

slate swan
tacit token
#

hi, slash is work?

hushed galleon
#

there are plenty of libraries that can offer slash commands for you

#

e.g. discord.py 2.0 (master branch) or forks of that project like disnake

tacit token
#
@slash.slash(name="test")
async def _test(ctx: SlashContext):
    embed = discord.Embed(title="embed test")
    await ctx.send(content="test", embeds=[embed])

Its now work, why?

#

this is my first slash

hoary cargo
#

Why you use embeds when you have just one embed hmmm

tacit token
#

What if, for example, not everyone teased? I found this shit on a page.

supple thorn
#

It's pointing out flaws that can be fixed

tacit token
#

No? this person at any time I wrote bound to me, even if there was a point of error

#

I don’t know where many people think of themselves, but there will be no one more than the other.

supple thorn
#

Why is your name pep 9001

final iron
supple thorn
supple thorn
tacit token
#

?

supple thorn
#

Hello ashley

slate swan
slate swan
tacit token
#

Hungarian lang have a lot of word for this

slate swan
tacit token
supple thorn
slate swan
tacit token
#

one word but i translate this, ugratás, te vagy az iskola zaklatója, aki mindenkibe csak beleköt (yeah its not english)

lofty tinsel
#

What should I change in the code then?

slate swan
#

Hey

cold sonnet
supple thorn
cold sonnet
#

happy for u

supple thorn
cold sonnet
#

and yeah, he translated it correctly by himself

#

but what we pointed out doesn't fix anything

#

how about you first ask him what version of dpy or what lib he uses

supple thorn
cold sonnet
#

oh I saw a t

cursive spindle
#
            winners = random.sample([user for user in users if not user.bot], k=1)
            print(winners)


>>> [<Member id=757311230582063275 name='The Owl' discriminator='6390' bot=False nick=None guild=<Guild id=945023980681723924 name='LegendBot' shard_id=None chunked=True member_count=4>>]

how i can access to member id

cold sonnet
#

now -> not

supple thorn
#

Yeah

cold sonnet
#

that's unfortunate

cold sonnet
#

!d random.sample

unkempt canyonBOT
#

random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
cold sonnet
#

yeah it returns a list

tacit token
cold sonnet
#

maybe your command isn't registered yet

lofty tinsel
#
@client.command()
async def creation(ctx: commands.Context, tag: str):
    tag = #depend the guy entered

    if len(tag) == 6 and tag.startswith("#U"):
        await ctx.send("created between august-october")
#

What should I change in the code then?

sick birch
#

Are you trying to get account creation?

#

You’re aware you can get the exact date and time easily by reverse engineering their ID?

slate swan
#

user for user in users huh

lofty tinsel
#

For clash of clans

slate swan
#

What are u trying to do

lofty tinsel
#

a clash of stats bot

#

With player info

slate swan
#

Do coc have an api?

lofty tinsel
#

the player will do >creation+ his tag and the bot will answer depend the tag

lofty tinsel
#

I would like to make a command that gives the approximate date of creation of an account. The creation date depends on the tag (#) of the player and it is with the help of this list that the bot will give the creation date. The creation date depends on the number of letters in the tag and the first letter.
The list is this: 6 digit tag = august-october 2012

#UXXXXX = august 2012
#UXXXXXX/#2XXXXXX/#LXXXXXX = december 2012

#XXXXXXX = 2013

#Qxxxxxxx = end 2013
#Gxxxxxxx = start/early 2013
#Rxxxxxxx = summer 2013
#Vxxxxxxx = 2014
#Pxxxxxxx = start-early 2014
#9xxxxxxx = early 2014

#2xxxxxxxx = early-end 2015
#8xxxxxxxx = start-early 2015
#9xxxxxxxx = 2016
#Pxxxxxxxx = end 2016
#Yxxxxxxxx = end 2017
#Lxxxxxxxx = end 2018
#Qxxxxxxx = end 2020

and the person will make the command >creation #TAGPLAYER and the bot will adapt its answer to the number of letters in the tag and its first letter

#

Its what i want to do

slate swan
#

I told you how to make it

#

I explained

#

I gave a good amount of code

#

I got ignored

slate swan
#

..

slate swan
cold sonnet
#

sorry?

lofty tinsel
slate swan
#

nvm that was unfunny

cold sonnet
#

Admin, she's rude to me again

slate swan
#

uh...

#

rude?

#

is it possible to use a command to toggle when a button is invalid?

paper sluice
slate swan
#

Ig he mean interaction failed

#

well, use a command to set a make a button turn off and turn on

#

i can’t remember what it’s called

paper sluice
slate swan
#

yes that

slate swan
paper sluice
#

sad

slate swan
#

can i use a command to toggle when a button is disabled then?

slate swan
#

nice

paper sluice
slate swan
#

Ig he mean event

#

so when i’m not available people can’t create a ticket

slate swan
#

i don’t know how to explain it

#

Open paint

#

Draw

#

Send here

#

Thats what i use when i cant explain

slate swan
# slate swan i don’t know how to explain it

you're like, whenever you go offline, the buttons get disabled, so that people cant create a ticket, whenever you're back online, the buttons are re-enabled, so that people can create a ticket, am I getting it right?

paper sluice
#

lmao wtf

cold sonnet
#

save your view, change its buttons on_member_update

supple thorn
#

He just said yes

slate swan
#

ahh nevermind

unkempt canyonBOT
#

disnake.on_presence_update(before, after)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") updates their presence.

This is called when one or more of the following things change:

• status

• activity

This requires [`Intents.presences`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.presences "disnake.Intents.presences") and [`Intents.members`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.members "disnake.Intents.members") to be enabled...
supple thorn
#

How does he not mean it

slate swan
#

it’s fine, it’s doesn’t matter anymore

cold sonnet
#

I mean it's kinda useful

slate swan
#

@slate swan do u want a command like !ticket disable so ppl cant create ticket

slate swan
hybrid ravine
#

text_channel_list = []
for guild in client.guilds:
for channel in guild.text_channels:
text_channel_list.append(channel)
async for channel in text_channel_list:
async for message in history:
if message.author == client.user:
return
print(f"{username} Posted {message.content}")
history_list.append(message.content)
i += 1
if i< 5:
await message.channel.send("Less Than 5 Messages In Current History... Returning All Time History")
await message.channel.send(history_list)

does something like this work to get all the messages in all the text channels? (sry for bad formatting)

slate swan
#

See

slate swan
#

and which library?

cold sonnet
#

that's gonna be a lot

slate swan
#

..

slate swan
# slate swan yes

@cold sonnet how did you disable all buttons in a View class using the children attribute? 😔 me forgot

hybrid ravine
#

history = message.channel.history()

cold sonnet
hybrid ravine
cold sonnet
hybrid ravine
cold sonnet
#

I also didn't disable buttons I just deleted the message

#

😳

slate swan
#

Thats a lot of process

hybrid ravine
slate swan
#

Cool

#

if your friends liked it then why are you re-creating it

cold sonnet
#

[<Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='a1' emoji=None row=0>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='a2' emoji=None row=0>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='a3' emoji=None row=0>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='b1' emoji=None row=1>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='b2' emoji=None row=1>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='b3' emoji=None row=1>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='c1' emoji=None row=2>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='c2' emoji=None row=2>, <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='c3' emoji=None row=2>]

#

so the children of my view only returned buttons

slate swan
#

?

cold sonnet
#

so Ig

for button in view.children:
    button.disabled = True
slate swan
#

..

cold sonnet
#

god I don't like how this sounds

#

GOD

#

I hate it

slate swan
#

..

#

Ok

#

i’ve found out how to do it: create a new class, then get the button message i want to edit and then edit that message with the disabled button

hybrid ravine
#

for text_channel in text_channel_list:
print(text_channel.name)

why does this return the text channel names twice?

spring flax
#

ahmm

boreal ravine
#

👀

paper sluice
#

this chat is cursed

cold sonnet
#

no

slate swan
#

agreed

#

all meh's fault

boreal ravine
#

time to report to modmail

slate swan
#

uhhh sifttt

cold sonnet
#

I'll even make my code more appropriate

slate swan
cold sonnet
#

it is now

#

it was before aswell

#

cuz it had no bad intentions

maiden fable
boreal ravine
#

@maiden fable @slate swan wanna coc now?

#

seems like you guys are free

slate swan
#

I gotta download it first, then create an account

#

😔

boreal ravine
slate swan
#

wdym

maiden fable
#

I'm on mobile rn, just waiting for dinner

slate swan
boreal ravine
slate swan
#

oh wow

boreal ravine
supple thorn
#

I was looking at ducks

#

😔

slate swan
azure tulip
supple thorn
#

That was actually mu assumption

visual island
azure tulip
silver wolf
vocal plover
# azure tulip Why it don't work? https://pastebin.com/b0nC8SXa

I'm not entirely sure why it doesn't work, but in the case of understanding what this does and asking for help I'd recommend trying to give the variables more useful names. If I just read ar, i, n I don't have a clue what they mean, but if they're lines, line, etc. they're far easier to make sense of

#

the role 962287817071927346 doesn't exist in that guild, so it returns None and then the call to add the role can't get the ID of the object because it's not a Role object

slate swan
#

then the role isnt in the bot's cache?

vocal plover
#

are you positive you copied the role id not a message id, guild id, channel id, etc.?

#

as long as you haven't messed with intents I'd be surprised if the cache was out of date for that

slate swan
#

how do i make an error handler for MemberNotFound?
I’ve tried if user == NotFound:

vocal plover
#

you'd have to use try/except:

try:
  do_something_with_user()
except MemberNotFound as e:
  handle_error(e)
slate swan
hybrid ravine
slate swan
hybrid ravine
#

if i get all the channels in a guild, how do i get all the messages attched to that channel?

cloud dawn
#

who dis

#

purple guy hmm

slate swan
#

okay thanks

cloud dawn
#

His hat is a duck :3

slate swan
#

what the-

#

duck? srsly?

cloud dawn
slate swan
#

😳

cloud dawn
slate swan
#

<str>.endswith('.jpg') ig? idk 💀 just guessing

#

i mean if you're passing it thorugh command or something can be checked liek that

cold sonnet
#

embed.set_thumbnail(url="https://m.media-amazon.com/images/M/MV5BMzhiYzRlNDctY2Y0My00ZTkwLTk0ODgtODg5ZTcxMWY5MjczXkEyXkFqcGdeQXRoaXJkLXBhcnR5LXZpZGVvLXVwZGF0ZXI@._V1_QL75_UX500_CR0,47,500,281_.jpg")

cold sonnet
#

oh it's a url kwarg

slate swan
#

i'm feeling more dumb for what u asked & what i understood

#

lol

#

like akinator? :3

paper sluice
cloud dawn
#

Best would be to use mimetype

slate swan
paper sluice
#

haven't heard of that in ages, imma go play that now

slate swan
#

😂 woah nice

slate swan
# cloud dawn lol

💀 i was assuming that he gonna put the url .. so url is string.. so... I hope u getting my point

#

and thought he wanna check if the image in url has .jpg extension.. so.. :'/

#

are u not planning to use some movie related api..? like the api will itself have the movie name, images nd stuff...

#

💀 just asking

azure tulip
#
bot.event
async def on_message(message):
  if {i.lower ().translate(str.maketrans('','', string.punctuation)) for i in message.content.split(' ')}\
   .intersection(set(json.load(open('cenz.json')))) != set():
      await message.channel.send(f' {message.author.mention}, не матерись')
      await message.delete()

    await bot.process_commands(message)
#

why not work?
everything is well written

slate swan
paper sluice
slate swan
#

eh... idk what u want as a reply.. but using aiohttp.. and u need api key to use their api

slate swan
#

:'/

#

using requests is a bad practice to use in async flow :'/

#

results in "blocking"

#

i can send u good docs about using it

#

yes sir

#

and if you've used requests, then switching to aiohttp won't be hard for u

#

since they've few things in common

#

:")

slate swan
#

aah.. idr sowwy

manic wing
#

its not hard, you make a request with a method, a path an endpoint, headers and parameters

#

headers would be api keys

slate swan
#

^ +1

heavy folio
#

!d aiohttp.ClientSession.get

unkempt canyonBOT
#

coroutine async-with get(url, *, allow_redirects=True, **kwargs)```
Perform a `GET` request.

In order to modify inner `request` parameters, provide kwargs.
paper sluice
slate swan
#

^ +1

#

and just suggesting.. in case you've used requests at other places for other commands.. try to replace it with aiohttp if possible :'/

#

that's okay :")

#

but their aiohttp docs is good

#

haha that's okay :3

maiden fable
#

ic Yerl with an anime pfp 👀

slate swan
#

💀 depends on lib that you're using

maiden fable
#

disnake

slate swan
#

:'/ if it's pycord then i can help

slate swan
maiden fable
#

u shifted to dpy from disnake?

slate swan
#

owo dpy has slash? 😳 sowwy dude.. i'm currently familiar with py-cord.. i've no idea about the changes made in dpy since danny continued the thing

azure tulip
slate swan
#

but it says indentation error :'/

azure tulip
#

can this be fixed somehow?

slate swan
#

💀 can ya send ss of your code? screenshot

#

ig i'm not able to guess your indenattion properly with that code block

slate swan
#

1st line will be

@bot.event
#

and

#

that 3rd line looks like space of only 3 :'/ it hsould be 4 spaces

winged bone
slate swan
torn sail
#

Sorry for ping. I cant read

hoary cargo
#

it's not hard using aiohttp, pretty much the same as requests with some extra steps

winged bone
#

Choices are defined once in the code and then stay the same. For autocomplete on the other hand you write a function which gets called every time the user writes something and you return the options.

#

So for an argument which should either be either ON or OFF you'd use choices, and for searching a movie db you'd probably use autocomplete

glass tundra
#

What are the libraries used for the ots?

#

bots*

glass tundra
maiden fable
#

what

sick birch
glass tundra
#

I'm pretty sure it has been discontinued by the author.

maiden fable
#

Nah its development has started again

glass tundra
#

?

sick birch
#

Read the gist

#

I don’t have the link on hand atm

#

I’m sure someone’s searching for it right now

glass tundra
fading harness
#

it now support everything latest

glass tundra
maiden fable
#

Indeed haha

glass tundra
#

But wait, there is nothing about slash commands in the docs.

boreal ravine
#

there is

#

go on master docs

glass tundra
#

what is that...

slate swan
#

omg @boreal ravine yk I was just searching up something related to mongodb to find out something that someone had helped me here and it was you loll

slate swan
# glass tundra what is that...

most new features are probably not documented or have examples so you should try to find if the feature has docs or examples on repo or you can just read src code

cloud dawn
#
import asyncio
from aiohttp import ClientSession

from client import Dispy
from constants import config

client = Dispy()


async def main() -> None:
    async with ClientSession() as session:
        async with client:
            client.https_session = session
            await client.start(config.bot.token)

asyncio.run(main())
``` what do you guys think about the new way to run the bot?
cloud dawn
cloud dawn
boreal ravine
#

also that isn't a new way

cloud dawn
boreal ravine
#

start has existed for a while

cloud dawn
#

aka danny is most likely going to force this at some point.

slate swan
glass tundra
glass tundra
#

Is there any documented lib then?

slate swan
boreal ravine
slate swan
#

most forks are lol

#

!pypi disnake

unkempt canyonBOT
cloud dawn
pliant gulch
#

Finally lmao

cloud dawn
pliant gulch
#

It kind of made no real sense to have a sync entry point E.g run

#

Should've just forced from day one to use start

#

The only problem I can see although is the asyncio.run part, as that creates a whole new event loop

#

Therefor maybe problems such as futures on a different event loop may occur

cloud dawn
#

Yeah that's annoying.. you need to put in intents now in 2.0.0

pliant gulch
#

Not to mention on_ready also depends on a bunch of Futures

#

To ensure cache is populated

slate swan
cloud dawn
#
from discord import Client, Intents

client = Client(intents=Intents())
pliant gulch
#

Why can it only be called after ready has been dispatched?

boreal ravine
cloud dawn
#

Even setup_hook doesn't work.

pliant gulch
#

Just manually request application info

slate swan
#

Anyone know how I can fetch all the objects from an array motor mongo

pliant gulch
#

And set it yourself

pliant gulch
boreal ravine
cloud dawn
slate swan
cloud dawn
#

just intents=Intents() lol

pliant gulch
# cloud dawn Hmm could try
async def setup_hook(self) -> None:
    data = await self.application_info()
    self.app_id = data.id
``` I'd assume
pliant gulch
#

Really might just start working on Rin again

slate swan
junior verge
#

How is this invalid syntax?

#

all my pip commands don't even work

torn sail
junior verge
pliant gulch
junior verge
torn sail
junior verge
#

Look what I send

torn sail
#

Yeah weird

cloud dawn
pliant gulch
chrome pecan
#

Can someone help me? my self is coming as None on command and i have no idea how to solve this

pliant gulch
#

I haven't even taken a look at discord.py's new stuff

junior verge
torn sail
#

Not sure

junior verge
#

It gives a error on every pip command I run

cloud dawn
# pliant gulch If you explain a bit to me what exactly sync does I'll be able to help
Traceback (most recent call last):
  File "C:\Users\eboss\Downloads\dpy\__main__.py", line 14, in <module>
    asyncio.run(main())
  File "C:\Users\eboss\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\eboss\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
    return future.result()
  File "C:\Users\eboss\Downloads\dpy\__main__.py", line 12, in main
    await client.start(config.bot.token)
  File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\client.py", line 681, in start
    await self.login(token)
  File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\client.py", line 544, in login
    await self.setup_hook()
  File "C:\Users\eboss\Downloads\dpy\client.py", line 22, in setup_hook
    await self.tree.sync()
  File "C:\Users\eboss\Downloads\dpy\venv\lib\site-packages\discord\app_commands\tree.py", line 869, in sync
    raise ClientException(APP_ID_NOT_FOUND)
discord.errors.ClientException: Client does not have an application_id set. Either the function was called before on_ready was called or application_id was not passed to the Client constructor.
``` when doing it inside the setup hook
junior verge
torn sail
#

Pass in a application id in the constructor

#

Not that hard

cloud dawn
pliant gulch
cloud dawn
torn sail
torn sail
cloud dawn
chrome pecan
cloud dawn
torn sail
slate swan
slate swan
#

not in core tho!

#

maybe just suggestions!

torn sail
#

Did it take over 3 seconds before it tried to responded

#

!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...
torn sail
#

Try deferring

cloud dawn
# pliant gulch Set `self.application_id` inside of `setup_hook`?
from ext.cmd import slash
from constants import config
from log import log

from datetime import datetime
from aiohttp import ClientSession

import discord
from discord import Client, Intents
from discord.app_commands import CommandTree


class Dispy(Client):
    tree: CommandTree[Client]
    https_session: ClientSession

    def __init__(self) -> None:
        super().__init__(intents=Intents(), application_id=config.bot.app_id)
        self.launch_time = datetime.now()

    async def setup_hook(self) -> None:
        self.https_session = ClientSession()

        self.tree = CommandTree(self)
        self.tree.add_command(slash, guild=discord.Object(id=config.debug.guild))
        await self.tree.sync()

    async def close(self) -> None:
        await super().close()
        await self.https_session.close()

    async def run(self) -> None:
        async with self:
            await self.start(config.bot.token)

    @staticmethod
    async def on_ready() -> None:
        log.info("Ready")
``` got this rn
pliant gulch
#

Ah

torn sail
#

Defer then send

slate swan
pliant gulch
#

self.__exit__ & self.__enter__

slate swan
# cloud dawn wdym?

async with self: the context manager of the client class why not overwrite it and you add your client session their?

torn sail
#

await interaction.response.defer() somewhere else await interaction.followup.send(…)

slate swan
#

andy gets what i mean

#

so it would be a backended session inside of the context manager so you wont have 2 context managers over eachother

cloud dawn
slate swan
pliant gulch
#

!e ```py
class Foo:
async def aenter(self) -> "Foo":
# Do stuff
return self

async def __aexit__(self, *_: "Any") -> None:
    ...
unkempt canyonBOT
#

@pliant gulch :warning: Your eval job has completed with return code 0.

[No output]
slate swan
#

^

pliant gulch
#

__aenter__ called via async with

slate swan
#

yup

pliant gulch
#

Then __aexit__ is called after leaving the context

slate swan
#

andy showed me all about them!

cloud dawn
#

ahh

pliant gulch
#

The parameters being passed to __aexit__ are for if any exceptions occur while in the context manager

#

I "omitted" them cause I'm lazy, but those are important

#

Depending on how you do it, you would accidentally suppress all errors

torn sail
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
cloud dawn
#

Gonna eat now idk what's cleaner tough.

torn sail
slate swan
torn sail
#

!d discord.app_commands.describe

unkempt canyonBOT
#

@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.

Example:

```py
@app_commands.command()
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
slate swan
#

yes

sick birch
#

Why not use f strings?

slate swan
#

await message.delete and remove ctx from the event and you didnt define msg

sick birch
#

Also on message doesn’t provide ctx

slate swan
sick birch
#

Also you’re checking if it’s in a dm and deleting it

#

Which is impossible

#

You can’t delete other peoples messages in a dm

torn sail
#

Show error

sick birch
#

Did you sync?

#

And it shows up on discord?

torn sail
#

Ohh can u show the code again

crimson tendon
#

Hello,
I am using an on_member_update event to get user's status and voice channel.
Does anyone know why I get None as before.voice and after.voice just after I get the right infos ? I got them 2 times when I change my status
and I am in a voice channel btw

sick birch
#

Why 2 message arguments

slate swan
#

U only need 1 arg which is message (u already have it)

#

its await message.delete() not await ctx.message.delete() (its bc you are using on_message event and the event needs only 1 arg which is message)

sick birch
#

You can type / on discord and see the slash command?

slate swan
#

speechless show the codes

#

yes

#

Also that is not going to work since the bot cannot delete msgs in DM's(ppl's msgs)

torn sail
#

hmm im not sure

slate swan
#

if message.guild and ...

#

i think down_syndromesmile

slate swan
#

Ye.

#

U forgot the other and

#

and message.content =="ur msg idk"

#

Ye speechless

#

await message.author.send()

slate swan
#

then add try except

#
try:
  await message.author.send("uwu")
except discord.Forbidden:
  await message.channel.send("rip")
#

uwu :|😭😭😭😭😭😭😭😭

slate swan
#

so what

slate swan
#

Ye but await client.process_commands(message) should be outside the try: down_syndromesmile

#

if the bot couldnt dm them then it will send the msg to that channel and it wont delete the msg anyway

#

😧

#

Wait

#

that code is cursed

#

Where is if

#

Btw use !paste cuz im on phone😭

neon spear
#

Hi, i asked this yesterday but didn't get a clear answer.

the bot worked for like a year, but for some reason it stopped working properly. I do have a channel where i only put 20 images (png). When i use this function he only reads like 11 images or less. Does someone has any idea how to fix this?

@bot.command()
async def updb(ctx):
    collection.drop()                               # Drops database collection
    channel = bot.get_channel(962354717307068426)   # Gets channel that's need to be readed
    async for message in channel.history(limit=20): # Reads history of channel limitation is 20
        url = message.attachments[0].url            # Checks per message for url (png)
        urlArray.append(url)                        # Adds url to array
        print(url)

    await bot.et_channel(id=818813967198978078).send("There are " + str(len(urlArray)) + " images posted in #visitcard_database!")
    for url in urlArray:
        collection.insert_one({"url": url})
```
slate swan
#

I cant see rhe codes :3

#

!paste @slate swan

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
#
@client.event
async def on_message(message):
    if message.guild is None and not message.author.bot and message.content == "fdp":
        await message.delete()
        print(f"Message was deleted !")
        try:
          await message.author.send(f"Insult : 
{message}")
        print(f"Private Message was sent !")
  except Exception:
          #get the channel here and send the error etc
    await client.process_commands(message)
    
slate swan
slate swan
slate swan
#

Yes

#

screenshot