#discord-bots

1 messages · Page 5 of 1

quaint epoch
#

!pypi requests

unkempt canyonBOT
quaint epoch
#

!pypi humans

unkempt canyonBOT
quaint epoch
#

👀

shrewd apex
#

i haven't used threading since i am not too sure if asyncio supports that lib i used concurrent.futures threadpoolexecutor which is said in their docs they support it

cold sonnet
shrewd apex
#

and used it with bot.loop.run_in_executor i had no problems with it till date

quaint epoch
#

!d asyncio.to_thread

unkempt canyonBOT
#

coroutine asyncio.to_thread(func, /, *args, **kwargs)```
Asynchronously run function *func* in a separate thread.

Any *args and **kwargs supplied for this function are directly passed to *func*. Also, the current [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") is propagated, allowing context variables from the event loop thread to be accessed in the separate thread.

Return a coroutine that can be awaited to get the eventual result of *func*.

This coroutine function is primarily intended to be used for executing IO-bound functions/methods that would otherwise block the event loop if they were ran in the main thread. For example:
quaint epoch
#

you can use this instead

shrewd apex
#

run_in_executor already creates a seperate thread

#

for tasks

dull terrace
#

but the question is whether it would still be blocking or do i have to start a thread for each blocking call inside a threaded one

#

threads honestly hurt my brain

quaint epoch
shrewd apex
#

so if u just want to create a thread for a task u don't need a thread lib

quaint epoch
#

just for one task?

#

well you could use asyncio directly

shrewd apex
#

just use bot.loop.run_in_executor(None, foo, *args)

dull terrace
#

so bascially might as well just do it for the slowest blocking task rather than the function which contains them

shrewd apex
dull terrace
#

oh it's in a loop already

shrewd apex
#

yes

quaint epoch
dull terrace
#
loop = asyncio.get_event_loop()
loop.create_task(client.start(token))
loop.run_forever()```
real grail
#

Ok, i will use this method :)

quaint epoch
#

and yes you can do that, but dpy handles it already

#

what ash said works

#

manually starting the loop isn't necessary

dull terrace
shrewd apex
#

idk why it dosent show with python bot but u can try in ur ide u just need to pass none as first arg then the function me and rest all args

#

u can use functools partial as well

#

if u want to

quaint epoch
#

passing None as an arg is sus 👀

#

but k

shrewd apex
#

thats how it works 💀 🗿

dull terrace
#

7739monkathink loop.run_in_executor(None, get_embed, interaction) i'm guessing getting return variables is gonna be a pain in the ass

shrewd apex
#

👌

#

don't forget to await

#

and if ur function is a coro

#

u need double await

dull terrace
#

... await await

paper sluice
#

why are you running a coro in executor pithink

dull terrace
#

yeah ill just make it not a coro

shrewd apex
paper sluice
#

if it has blocking stuff, don't make it a coro, simple

shrewd apex
#

how is your jam coming along?

paper sluice
#

decent ig

shrewd apex
#

nais

paper sluice
#

wbu

shrewd apex
#

eh similar somewhat decent

#

situation looks a bit dicy

paper sluice
#

ah gl

shrewd apex
#

hehe gonna need that

dull terrace
#
embed, components, file = await asyncio.gather(loop.run_in_executor(None, get_embed, interaction))```
will this work ![7739monkathink](https://cdn.discordapp.com/emojis/960314142030442566.webp?size=128 "7739monkathink")
shrewd apex
#

y gather? and where ur bot?

dull terrace
#

how do i get return values

shrewd apex
#
embed, components, file = await self.bot.loop.run_in_executor(None, get_embed, interaction)
#

in the get_embed function

#

just add a return statement

dull terrace
#

i don't get why i need the bot, it's not in a class either so self?

shrewd apex
#

bot has a loop attribute u need that

dull terrace
#

ohhhh

#

so i created an event loop when i didn't need to

shrewd apex
#

how do ik if it's in a class or not 🗿

warped mirage
#

guys

#

i need help making a set prefix command, multi guild, using files aka, txt

slate swan
shrewd apex
slate swan
#
main.py:31: RuntimeWarning: coroutine 'Loop.__call__' was never awaited
  S_ping()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
#

it is a task

slate swan
#

hellllloooooooooooooooooooooooooooooooooo

slate swan
paper sluice
#

show code

slate swan
shrewd apex
#

no

slate swan
shrewd apex
#

u just remove the await there that's it nothing less nothing more

slate swan
#
@tasks.loop(seconds=60)
async def S_ping():
  await bot.wait_until_ready()
  c1 = bot.get_channel(1001528129254338641)
  c2 = bot.get_channel(1001528141631737997)
  c3 = bot.get_channel(1001528154013311037)
  c4 = bot.get_channel(1001528163941228635)
  c5 = bot.get_channel(1001528191300685824)
  while True:
    await c1.send("@everyone")
    await c2.send("@everyone")
    await c3.send("@everyone")
    await c4.send("@everyone")
    await c5.send("@everyone")
    await asyncio.sleep(2.5)
#

what do i do

#
main.py:31: RuntimeWarning: coroutine 'Loop.__call__' was never awaited
  S_ping()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
slate swan
#

for pings

#

you can join

#

its still cringe especially because of ratelimits

shrewd apex
#

S_ping.start()

slate swan
dull terrace
#

pretty happy with my 3rd bot now froggy_chill

slate swan
#

its amazing

slate swan
shrewd apex
#

i wouldn't want a ping every 2.5 secs either

#

thats even more annoying than rate limits

slate swan
#

imagine like not having your own server

#
@commands.has_permissions(administrator=True)
async def gstart(ctx,time,winners,prize):

    channel = ctx.channel

    embed = discord.Embed(title="Giveaway!",description=f"{prize}",color=random.choice(colors))
    embed.add_field(name="Hosted by:", value=ctx.author.mention)
    embed.set_footer(text=f"Ends {time} from now!")
    my_msg = await ctx.channel.send(embed=embed)
    await my_msg.add_reaction("tada")

    d = time[-1]

    num = int(time[:-1])

    if d == "s":
        await asyncio.sleep(num)

    if d == "m":
        await asyncio.sleep(num * 60)

    if d == "h":
        await asyncio.sleep(num * 60 * 60)

    if d == "d":
        await asyncio.sleep(num * 60 * 60 * 24)

    winners_number = int(winners[:-1])
    new_msg = await channel.fetch_message(my_msg.id)

    users_mention = []
    for i in range(winners_number):
      users = await new_msg.reactions[0].users().flatten()
      users.pop(users.index(bot.user))
      winner = random.choice(users)
      users_mention.append(winner.mention)
      users.remove(winner) 
    await ctx.send(f"Congratulations {users_mention} you won the giveaway !")```
Why giveaway dosent work without errors?
jade fulcrum
#

little question here

#

i want to do this but how do i store data in each varible?

timid briar
#

have problem with twilio

jade fulcrum
#

not related to discord bots

#

but love if someone could help

slate swan
#

ask in python general or a help channel, this channel is for discord bots

#

😢

slate swan
#

what am i seeing right now

#

Lol, I forgot Twilio exists.

timid briar
#

so any help

slate swan
#

I mean the error message is right there anyway and tells you what you need.

slate swan
#

check line 21,22,23 if i counted it right

regal pulsar
#

guys

#

anyone know how to reopen a closed dms with a deleted account

#

with or without python

slate swan
#

What is going on with your imports....

import datetime
import os
import discord 
from discord.ext import commands
from discord.ext import tasks
import os, discord, datetime
from discord.ext.commands import Bot
from dotenv import load_dotenv
regal pulsar
#

i just need a message i sent there

#

and yeah i have the id

regal pulsar
#

i had a friend who deleted their account

slate swan
#

That would be a discord support thing if the account is deleted, even then it will be against data protection so not doable.

regal pulsar
#

im looking for a message i sent them

slate swan
#

do you still have him as a friend?

regal pulsar
#

when an account is deleted the friends list is cleared

slate swan
#

Well, contact support like I said, but you whether its your account or not is irrelevant, they will refuse on grounds of data protection.

#

oh right, well you cant unless you had the dm open

slate swan
#

@regal pulsar if u can find them on a server or whatever just right dm them, u will get an error but aye u can read the dms

regal pulsar
#

like for example this is the id

#

456226577798135808

#

i tried doing @slate swan

#

@slate swan

slate swan
#

Discord support.....

regal pulsar
#

clicking the message button does nothing

sick birch
#

Searching up "deleted user" in the quick switcher shows up

regal pulsar
sick birch
#

I'm able to view the DMs of people I've talked to who have deleted their accounts

regal pulsar
#

a bunch of them are showing up for me but not this one

slate swan
#

But didn't you say you deleted your account you used to message them?

regal pulsar
#

no they deleted their account

#

they have a new one now but im looking for something i sent them a while ago

slate swan
#

Ok, did you clear the conversation/delete the specific chat with that friend? I mean can you see anything at all from that specific frined?

regal pulsar
#

i had a dm open with them on my old account and i can scroll down and open it just fine

#

but not on this one

slate swan
#

this would work right?

sick birch
slate swan
#

kids, give me ur tokens and ill run ur bot 24/7

#

really?😳

slate swan
slate swan
swift pumice
slate swan
#

Discord support.

regal pulsar
#

you mean messages from mutual servers?

pliant gulch
regal pulsar
slate swan
#

Contact discord support this is not a discord bot issue.

slate swan
#

the heck is a BSPWM

sick birch
#

good wm

regal pulsar
slate swan
sick birch
#

i am also a bspwm enjoyer

slate swan
pliant gulch
#

DWM is definitely more powerful than BSPWM since you get to use C, if my install wasn't fully configured to BSPWM already I would've used DWM or Xmonad

swift pumice
slate swan
swift pumice
slate swan
#

nah kids im being fr, ill host ur discord bot for no extra cost 👍 i have a server that doesnt do anything atm, just mc and my discord bot

regal pulsar
#

mc is ridiculously unoptimized

slate swan
#

need to setup openrc services because man im lazy

slate swan
#

Where you host your discord bot? I'm intrigued.

slate swan
sick birch
#

Not to be a stick in the mud but please be careful on who you give our your tokens to, just a word of advice

regal pulsar
slate swan
regal pulsar
#

the game is unoptimized

slate swan
#

lemme ssh rq

#

damn ip changed

slate swan
swift pumice
#

thats sus as hell

slate swan
#

im just dumb

slate swan
slate swan
#

look mommy im a haxor

pliant gulch
#

You had to ask me and I don't even use xmonad

slate swan
#

me being an average windows user: lemon_glass

grim oar
#

I wanna have 1% patience of gentoo users

grim oar
pliant gulch
slate swan
grim oar
#

I can but I don't think i have enough patience for compiling literally anything I install for hours

slate swan
#

ahem can you guys stop

hollow badger
#

@slate swan Please stop offering to host bots, and stop asking for people's tokens.

terse coyote
#

how to get client latency in discord.ui.button? i tried interaction.client.latency always 0

grim oar
sick birch
slate swan
terse coyote
# sick birch Really? That's strange, not documented behaviour
class Ping(discord.ui.View):
    def __init__(self, client):
        super().__init__()
        self.value = None

    @discord.ui.button(style = discord.ButtonStyle.gray, label = "Перевірити ще раз", emoji = "♻️")
    async def update(self, interaction: discord.Interaction, button: discord.ui.Button):
        embed = discord.Embed(description = f"Пінг бота до серверів діскорду {round(interaction.client.latency)}")
        await interaction.response.send_message(embed = embed, ephemeral = False)
        self.value = True
        

class ping_command(commands.Cog):
    def __init__(self, client):
        self.client = client


    @commands.command()
    async def ping(self, ctx):
        view = Ping()
        embed = discord.Embed(description = f"Пінг бота до серверів діскорду {round(self.client.latency)}")
        await ctx.send(embed = embed, view = view)```
sick birch
#

Ah because it's in seconds

#

Usually bots will not have latency measured in seconds

grim oar
sick birch
#

Rounding is where the problem is as it's probably < 500ms/0.5s

#

so it gets rounded down to 0

sick birch
#

What you should do is multiply interaction.client.latency by 1000 to get the latency in milliseconds, and send that instead

slate swan
#

i dont get whats wrong with offering to host peoples bots

sick birch
grim oar
#

Against the rule so yeah follow it

sick birch
#

And as a word of advice, never give your token to any possible VPS that you don't 110% trust

slate swan
sick birch
#

@terse coyote

latency = round(interaction.client.latency * 1000) # in milliseconds
vocal snow
slate swan
#

how do i get user avatar url in a slash command

#

How can I make my bots prefix change every 10 seconds

#

I just want to make a list and shuffle through the prefixes from the list

sick birch
#

That sounds like a terrible design choice

slate swan
#

robin

slate swan
#

how do i get user avatar url in a slash command

sick birch
#

Well if you really want to you can create a loop and do something like bot.command_prefix = 'something else'

slate swan
sick birch
#

Didn't mean a loop, my bad. A task

#

!d discord.ext.tasks.Loop

unkempt canyonBOT
#

class discord.ext.tasks.Loop```
A background task helper that abstracts the loop and reconnection logic for you.

The main interface to create this is through [`loop()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.loop "discord.ext.tasks.loop").
slate swan
#

@sick birch

#

how do i get user avatar url in a slash command

sick birch
#

Can I help you?

sick birch
slate swan
#

dpy 2.0.0

sick birch
#

interaction.user.avatar.url

slate swan
#
from discord.ext import tasks

@tasks.loop(seconds = 20) # repeat after every 20 seconds
async def myLoop():
    # code here

myLoop.start() # can this go anywhere?
sick birch
#

Usually people will create a cog and start the loop in the cog's constructor

slate swan
#

I don't want to use cogs

#

or should I start the loop in the on ready

sick birch
#
class PrefixSwitcher(commands.Cog):
  def __init__(self) -> None:
    ...
    my_loop.start()

  @tasks.loop(seconds = 20)
  async def my_loop() -> None:
    ...
sick birch
#

You should be able to just start it in the global scope

slate swan
#

pk

maiden fable
#

Do I smell another scam free host? 👀

sick birch
#

It's been handled

slate swan
#

I can just use random to choose the prefix from the list right

vocal snow
#

'Oh' in message.content

maiden fable
#

Nice

slate swan
#

@sick birch should I use random.choice or secrets.choice?

sick birch
#

I'm not familiar with the latter

slate swan
#

it's just a cryptographically secure version of random

sick birch
#

If that's true, then in this case it doesn't matter and it's overkill

slate swan
#

yyeah

maiden fable
slate swan
#

how do you guys even find such libraries pepe_exit

vocal snow
#

It's so sensitive. Id never let my users know my bot prefix!

night crater
#

you gradually become aware

#

I can guess it! it's gonna be / in a few months

sick birch
maiden fable
maiden fable
#

Think of any word and there is a huge possibility that lib exists

vocal snow
#

What didn't you understand pithink

maiden fable
#
if "oh" in message.content.lower():
    . . .
paper sluice
#

are you aware of the in keyword in python?

maiden fable
#

Ryuga speaking like a Helper does

slate swan
slate swan
#

@sick birch If I define prefix in the loop prefix is never defined to access for the command_prefix.. How can I do it?

grim oar
cold sonnet
#

hey one hundred percent not, I'm Dani

grim oar
#

Milk doesn't taste good

cold sonnet
#

haven't tasted milk yet

grim oar
#

Dani.

slate swan
#

i love milk

vocal snow
slate swan
#

nova do you even eat?

grim oar
# slate swan mid opinion

I have one million racially motivated responses ready but a certain hypocrite will ban me again so i will opt against answering.

grim oar
vocal snow
#

That's almost anti-national

grim oar
#

-ot

#

.ot

#

What the Jesus i

slate swan
vocal snow
#

What was your jee score again nova

grim oar
#

I did not write that exam. Ot.

sick birch
#

Most people will pass it into their cog, but you said you didn't want to use cogs so you'll need to figure out how to get access to the bot instance

grim oar
#

Ayo Mr helper, won't you ask them to stop ot-ing here perhaps.

vocal snow
#

Shut up nova

grim oar
#

I am hurt.

sick birch
#

maybe but globals are a bad idea

vocal snow
#

Globals are frowned upon

slate swan
slate swan
grim oar
#

Yes they are a terrible idea.

slate swan
#

why does everyone hate them

#

guess im nobodyshipit

vocal snow
#

Hi okimii how is codejam going

slate swan
#

zeffo didnt qualify?

slate swan
vocal snow
#

I qualified but i didn't want to participate

slate swan
#

ah cool

austere vale
#
  @commands.Cog.listener()
  async def on_bulk_message_delete(self, messages):
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow())
    async for entry in delete.guild.audit_logs(action=nextcord.AuditLogAction.message_bulk_delete):
      embed.description=f'Channel: {messages.channel}\n{count}Messages Deleted'
    await self.bot.get_channel(933978399280599080).send(embed=embed)

can someone help me format the async for entry? particularly what delete.guild.audit_logs and {count} should be instead

slate swan
#

black formatter is crying right now

paper sluice
#

me too

slate swan
vocal snow
grim oar
unkempt canyonBOT
#

When adding functions or classes to a program, it can be tempting to reference inaccessible variables by declaring them as global. Doing this can result in code that is harder to read, debug and test. Instead of using globals, pass variables or objects as parameters and receive return values.

Instead of writing

def update_score():
    global score, roll
    score = score + roll
update_score()

do this instead

def update_score(score, roll):
    return score + roll
score = update_score(score, roll)

For in-depth explanations on why global variables are bad news in a variety of situations, see this Stack Overflow answer.

grim oar
#

can't you use botvar

slate swan
#

I swear I've never used global ever, why does it even exist

paper sluice
#

ive used it before, when our school was teaching about scopes

vocal snow
#

It does have valid usecases

slate swan
#

Just use a class pepe_exit

grim oar
#

No use case at all, there are much better alternatives

vocal snow
#

It's kinda like metaprogramming in the sense that you should use it only when there aren't any alternatives

grim oar
#

There always are alternatives for globals and meta both

vocal snow
slate swan
#
elon = commands.Bot(command_prefix=prefix, intents=intents, case_insensitive=True)

@tasks.loop(seconds=20)
async def myLoop():
    prefix = random.choice(prefixes) # somehow make this accesible in the command_prefix above
   
myLoop.start()
grim oar
#

i will go back on my hiatus, was bored so joined the convo ¯\_(ツ)_/¯

vocal snow
slate swan
#
class UwU:
  var: int = 10

uwu = UwU()

def func(score: int, deduction: int) -> int:
  uwu.var = score
  return score-deduction

def foo() -> int:
  return uwu.var

pepe_exit looks cleaner than a global

slate swan
vocal snow
#

🤨

slate swan
#

and your annotations could be better

grim oar
slate swan
slate swan
vocal snow
#

The return annotations aren't even necessary

slate swan
#

you arent necessary

#

🙄

vocal snow
slate swan
#

overrated

#

chocolate milk better

white aurora
#

👀

vocal snow
#

Coffee mocha 🤤

sick birch
#

Could we stay on topic folks

slate swan
#

@vocal snow do I literally just add the bot.command_prefix in the task loop or ?

slate swan
#

😤

sick birch
#

i've been caught

slate swan
#

!ot

unkempt canyonBOT
slate swan
#
elon = commands.Bot(command_prefix=random.choice(prefixes), intents=intents, case_insensitive=True)

@tasks.loop(seconds=20)
async def myLoop():
    elon.command_prefix

myLoop.start()
vocal snow
#

Yes, set it to random.choice(...)

slate swan
#

hm okay

slate swan
vocal snow
#

Yes

slate swan
# vocal snow Yes

that's so weird it seems like it's not changing after the task resets

vocal snow
#

Or maybe its just picking the same prefix

#

Print it out and see

austere vale
#

can someone help me with the underlined errors i have?

paper sluice
#

delete is not defined?

#

we can't see the error

austere vale
#

ohh

#

theyre both undefined

#

im just not sure what they're supposed to be

grim oar
#

messages.guild most likely

slate swan
vocal snow
#

Are you calling random.choice in the loop callback?

slate swan
grim oar
#

Bruh

vocal snow
#

Bruh

grim oar
#

elon.command_prefix = random.choice(prefixes)

vocal snow
#

That picks a random character from the existing prefix string

slate swan
#

Oh my

#

that would make sense....

austere vale
# grim oar messages.guild most likely
  @commands.Cog.listener()
  async def on_bulk_message_delete(self, messages):
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow())
    async for entry in messages.guild.audit_logs(action=nextcord.AuditLogAction.message_bulk_delete):
      embed.description=f'Channel: {messages.channel}\n{messages.count}Messages Deleted'
    await self.bot.get_channel(933978399280599080).send(embed=embed)
```could someone help me?
maiden fable
slate swan
#

Does having a task loop mess up on_message events?

maiden fable
#

No

grim oar
grim oar
vocal snow
#

Isn't looking through audit logs pointless if the event tells you which messages were deleted

slate swan
# maiden fable No
@elon.event
async def on_message(message):
    if elon.user.mentioned_in(message):
        await message.channel.send('I was pinged.')

when I run other commands it does nothing?

slate swan
vocal snow
slate swan
slate swan
slate swan
#

Hence your commands.. Add a process_commands method at the last

austere vale
slate swan
#

or I can just use a listen instead of an event?

slate swan
#

It's a list of multiple message instances

austere vale
#

how do i get access the messages part of the audit log then?

slate swan
#

How do you get an item from a list?

austere vale
#

you call array index ?

slate swan
#

Exactly

#

Do the same thing here

#

how do i get all dms from my bot, like when people dm my bot how do i get them to post into channel

#

!e ```py
messages = ['hi', 'hello', 'nevergonnagiveyouup']
print(messages[2])

or to iterate through each message

for message in messages:
... # do stuff with message

unkempt canyonBOT
#

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

nevergonnagiveyouup
slate swan
slate swan
dry urchin
#

why am I getting a git error when its in my path

slate swan
dry urchin
#

@bot.command()

slate swan
#

You dont define both client and bot

#

You just need one of them

#

Preferably Bot, cause it supports commands extension

#

Yes

#

Initialise using Bot class and remove every instance of Client

slate swan
slate swan
#

In the event, check if the message.channel is a Dm channel

#

You still didnt remove your client

#

I hope you know enough python required to use this library. If not, prefer doing simple projects first before jumping right into dpy

#
  @commands.Cog.listener()
  async def on_message(self, message):
    logchannel = self.client.get_channel(1001565362904629381)

@slate swan

#

Yes

#

Now check if message.channel is an instance of DMChannel

#

If it is, the message is received in your DMs. Then just log it into your log channel

#

now i dont understand.. @slate swan

slate swan
slate swan
#

Sorry I need to go soon its already midnight 💀 Share your issue here someone else might be able to help you out

keen viper
#

hi

#

how do i fix this?

#

i’m trying to make a discord music bot

slate swan
#

You have the message instance. You now need to check the channel type. How you do that?
Use isinstance() method to compare your message.channel and discord.DMChannel class. If it returns True that means the channel in which the message was sent is a DM Channel. Since the only possibility for the bot to receive a message in a DM Channel is it's own DM.
Now you know that the bot received a message in their DMs. Just send the content of the message to the required channel and you're done.

#

@slate swan ^

slate swan
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)
slate swan
#

ok so

keen viper
slate swan
#

Read the embed

#

so

#

i need a if statement

#
  @commands.Cog.listener()
  async def on_message(self, message):
    logchannel = self.client.get_channel(1001565362904629381)
``` can you just do the first part , please.
#
  • Remove useless imports. You have many unused/double imports in your code
  • The intents you defined is below your bot declaration. Also you need to pass intents in the constructor like Bot(intents=...) so do that too. Same reason why your Bot isn't receiving member events.
  • The fetch_guild and fetch_channel are API calls and also async functions. Either await them, or even better just use get_guild and get_channel because it uses cache, saves you and API call.
unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
slate swan
#

alright whats the oject and whats the classinfo

#

Uhh that's out of context for this channel but object is the instance of the object you need to check, and classinfo is/are the class/array of classes you need to compare your instance with

#

true

#

!e ```py
i = 10
print(isinstance(i, int))

unkempt canyonBOT
#

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

True
slate swan
#

alright

#

tysm, i did it

odd mango
#

i have been trying to make a bot restart command

    @commands.command(name="restart")
    @commands.is_owner()
    async def restart(self, ctx):
        await ctx.send("Restarting bot...")
        await self.bot.close()
        os.execv(sys.executable, ['python'] + sys.argv)```
#

this is what i have and works perfect. but at discord.py place they say not to use os.execv

#

is there any alternative to do this

austere vale
#

sometimes it shows the right number of messages deleted, sometimes it doesnt. anyone know how to fix ?

  @commands.Cog.listener()
  async def on_bulk_message_delete(self, messages):
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow())
    for Message in messages:
      async for entry in Message.guild.audit_logs(action =nextcord.AuditLogAction.message_bulk_delete):
        embed.description=f'Channel: {Message.channel.mention}\n{len(messages)} messages deleted'
    await self.bot.get_channel(933978399280599080).send(embed=embed)
sick birch
odd mango
#

because personally i dont know any of the methods

sick birch
#

Not that I know of, but they shouldn't be hard

#

For example systemd is a linux classic, included in many distros. You could start with that

slate swan
#

@sick birch AttributeError: 'Command' object has no attribute 'listen'
coming from my on message listen, I changed nothing im not sure why it's showing this

sick birch
#

Is it in a cog?

slate swan
#

No

sick birch
#

It should be @bot.listen() then

slate swan
#

yeah it is

#

@elon.listen('on_message')
async def pinged(message):
    if elon.user.mentioned_in(message):
        await message.channel.send('You mentioned me!')
sick birch
#

You're sure that's the right line?

slate swan
#

yeah it says line 36

sick birch
#

Could you send the definition for elon

#

Not sure why it's a Command object

slate swan
sick birch
#

Do you have a command of the same name?

slate swan
#

Oh my god

#

that's why lmao 🤣

#

how did I forget about that

sick birch
#

Yeah prefix the command with a _elon, and use the name='elon' kwarg in the command constructor

slate swan
#

yeah

sick birch
#
@bot.command(name="actual_command_name")
async def some_random_command_name(...) -> None:
  ...
slate swan
#

what does the -> None: do?

sick birch
#

It's usually good practice to typehint everything, including the return type

#

Command handlers will usually always be -> None as they shouldn't return anything (even if they do, which they shouldn't, they'll be ignored)

slate swan
#

is it bad to not do it?

sick birch
#

It's.. not ideal

slate swan
#

Why so?

sick birch
#

You should always typehint everything when you can

#

Much easier for you as the developer and so you know what variables are of what types

#

Your IDE can also help you by suggesting possible methods and attributes so you won't have to refer to the documentation

pliant gulch
#

Make sure to have an actual working/get a type-checker otherwise you'll fall into a hole you'll never get out of

slate swan
austere vale
#

oh

grim hill
#

Hello, i was wondering how i can save a message object in a json to remember it and load it again on initialization of my cog

#

It's for a system where people vote on the message to approve it so my bot needs to remember it

#

might be pycord

sick birch
grim hill
#

but do you have an example of how to save the id?

austere vale
#
  @commands.Cog.listener()
  async def on_bulk_message_delete(self, messages):
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow(),description=f'Channel: {messages.channel.mention}\n{len(messages)} messages deleted')
    await self.bot.get_channel(933978399280599080).send(embed=embed)

what do i replace {messages.channel.mention} with to mention the channel properly?

grim hill
#

This is my code right now

import asyncio
from distutils.log import debug
import discord
from discord.ext import commands
import json

class story(commands.Cog):
    def __init__(self, client):
        self.client = client

        # load saved message here in memory to check it for reactions
        

    @commands.Cog.listener()
    async def on_message(self, message):
        # Ignore ourselves
        if (message.author.bot):
            return
        # Ignore all messages except in the story channel
        if (message.channel.id != 1001566491335999599):  
            return  
        
        # add reactions to message and save it in json + lock channel

        await message.channel.send("Message sent!")

def setup(client):
    client.add_cog(story(client))
    print("story.py loaded")
random portal
austere vale
random portal
# austere vale

yes messages is a list of discord.Message

try messages[0].channel.mention

slate swan
#

is there a possible way i can get more than one member like picked in a slash command example in ss but be able to pick more than ONE member

austere vale
# random portal yes messages is a list of `discord.Message` try messages[0].channel.mention
  @commands.Cog.listener()
  async def on_bulk_message_delete(self, messages):
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow(),description=f'Channel: {messages[0].channel.mention}\n{len(messages)} messages deleted')
    await self.bot.get_channel(933978399280599080).send(embed=embed)

do you know how to fix the len so that it properly shows how many messages were deleted?

random portal
#

hm

#

just bc u specified to purge 100 messages doesn't actually mean 100 messages will be purged

#

in the discord.py docs, its defined as The number of messages to search through. This is not the number of messages that will be deleted, though it can be.

#

maybe the purge command actually only deleted 4 messages?

hybrid fjord
#

any more than 1 parameter in dpy 2.0 slash commands won't come up on the bot. any idea why?

slate swan
#

is there a possible way i can get more than one member like picked in a slash command example in ss but be able to pick more than ONE member

random portal
#

idk if it works for slash commands but try commands.Greedy

slate swan
austere vale
#

maybe not 100 but i do think somethings wrong with my code bc it did purge more than 4

random portal
wicked atlas
austere vale
# random portal can u send ur code for the `purge` command
  @commands.command()
  async def purge(self,ctx,*,number:int=None):
    if ctx.message.author.guild_permissions.administrator:
      try:
        if number is None:
          await ctx.send('Gotta gimme a number of messages to delete.')
        else:
          deleted=await ctx.message.channel.purge(limit=number)
          await ctx.send(f'Messages purged by {ctx.message.author.mention}: `{len(deleted)}` (max is 100)')
cold sonnet
#

why would you save deleted

grim hill
#
    @commands.Cog.listener()
    async def on_message(self, message):
        # Ignore ourselves
        if (message.author.bot):
            return
        # Ignore all messages except in the story channel
        if (message.channel.id != 1001566491335999599):  
            return

        message_id = message.id
        message_content = message.content

I want to add 2 reactions to the message (👍 👎) how do i do this?

#

it's for voting

#

i figured it out

#

i think i previously used a wrong name for the command

random portal
#

on_bulk_delete_message only returns cached messages i think

#

try using on_raw_bulk_delete_messages

wicked atlas
#

Can you send the whole code for your class?

#

and as text, preferably

#

Bit confusing as to why you're creating a class inside of a function, but like the error says, it's expecting the custom_id parameter of your super.__init__() in your MyModal class to be a string, not an InputText

austere vale
# random portal try using `on_raw_bulk_delete_messages`
  @commands.Cog.listener()
  async def on_raw_bulk_message_delete(self, messages):
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow(),description=f'Channel: {messages[0].channel.mention}\n{len(messages)} messages deleted')
    await self.bot.get_channel(933978399280599080).send(embed=embed)
hybrid fjord
#

any more than 1 parameter in dpy 2.0 slash commands won't come up on the bot. any idea why?

hybrid fjord
#

i believe so

slate swan
#

how do u get a guild in a slash command? the member count

pastel aspen
#

Does this has_permissions() check if the user being banned has a rank above the author? Like if a helper tries to ban an admin for example, can they do that?

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        if member == None or member == ctx.message.author:
            await ctx.channel.send("You cannot ban yourself")
            return
        await member.ban(reason=reason)
        emb = discord.Embed(title=f'O usuário {member} foi banido.', description=reason)
        await ctx.send(embed=emb)```
sick birch
#

So if you've got ban_members permission, you can ban other people

wise gull
#

how to ping voicechannels

rain olive
#

same way you do with normal channels

white aurora
#

<#voice-channel-id>

thorn grove
#

Guys

#

I need help

#

If i do this it works

#

But if its this, the command doenst work

#

Line 8

pastel aspen
#
    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        if member == None or member == ctx.message.author:
            emb = discord.Embed(title=f'Você não pode fazer isso.')
            await ctx.send(embed=emb)
            return
        if ctx.guild.message.author.top_role > ctx.guild.memeber.top_role:
            await member.ban(reason=reason)
            emb = discord.Embed(title=f'O usuário {member} foi banido.', description=f"Motivo: {reason}")
            await ctx.send(embed=emb)```

how can I make this check the highest role of both author and member being banned, and check if author has role higher than member? so that a helper wont ban an admin for example
sick birch
#

You can just assume that the user has the right permission to ban, and use a try/catch to catch a discord.Forbidden error

#
try:
  await member.ban(...)
except discord.Forbidden:
  await ctx.send("You don't have the necessarily permissions to ban that user.")

Not sure if that's the exact error but a quick look at the documentation will tell you

indigo pilot
pastel aspen
indigo pilot
#

Example: if interaction.user.top_role.position =< user.top_role.position:

hybrid fjord
#

timeout user in dpy 2?

hushed galleon
hushed galleon
unkempt canyonBOT
#

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

Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").

You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
indigo pilot
hybrid fjord
indigo pilot
#

One more quick question tho

pastel aspen
#

does "ctx.message.author.top_role.position" get the author top role? is the syntax right?

indigo pilot
#

Ide bug or did i mess something up

hushed galleon
#

it should tell you specifically what its complaining about if you hover your mouse over the underlined lines

indigo pilot
indigo pilot
#

Not sure what that means tho

#

Or why im getting it

hushed galleon
#

that is a pretty poor error message

indigo pilot
indigo pilot
hushed galleon
#

what its basically saying is that the view= parameter doesnt exist for TextChannel.edit()

indigo pilot
#

But.. it does right?

#

Unless docs lied to me 🙏

hushed galleon
#

you uh, need to store the Message object thats returned from fetch_message and edit that

indigo pilot
#

Oh my god

#

Im so dumb

#

I forgot to do post = on the middle line

#

I am so sorry 😭

#

Tysm for helping

hushed galleon
#

np you good

pastel aspen
#

what does this * means?

ivory wraith
#

to store user data (for example, a currency and trading bot where trades might take a while, and with buy and sell orders), what should I use? It's going to be a relatively small bot.

pliant gulch
# pastel aspen what does this * means?

In regular python when adding an asterisk inside of the function signature causes any arguments after that KEYWORD-ONLY. ```py
def foo(bar: str, *, baz: str) -> None:
print(bar + baz)

foo("Hello", "World!") # Error!
foo("Hello", baz="World!") # No error!
Strictly speaking in the context of discord.py, since the wrapper inspects the function signature to do "custom" (how the library wants it) parsing, it'll mean that the `member` argument in this case, consumes everything the user types, E.gpy
@commands.command()
async def foo(ctx: commands.Context, *, arg: str) -> None:
await ctx.send(arg)
``` Running it via !foo Hello World! will capture Hello World! (The full sentence) in the arg variable. Whereas doing it without the asterisks will produce an error since it didn't expect two inputs

pastel aspen
pliant gulch
#

Forces until to be positional ONLY

#

So you cannot do timeout(until=...)

#

It has to be timeout(...) or else it'll error

#

!e ```py
def foo(bar: str, /) -> None:
print(bar)

foo("Hello World!")
foo(bar="Hello World!")

unkempt canyonBOT
#

@pliant gulch :x: Your 3.11 eval job has completed with return code 1.

001 | Hello World!
002 | Traceback (most recent call last):
003 |   File "<string>", line 5, in <module>
004 | TypeError: foo() got some positional-only arguments passed as keyword arguments: 'bar'
thorn grove
#

How can i check if a sentence has a word(e.g. Bot)

pastel aspen
pastel aspen
pliant gulch
white aurora
thorn grove
#

guys

#

for some reason this doesnt work

#

line 17 to line 21

thorn grove
#

but it still doenst work if i do so

#

anyone ?

next coral
sick birch
hushed galleon
#

^ and its SQL, good for structured data which is what you'll mostly have with discord bots

thorn grove
ivory wraith
thorn grove
#

new code:

#

now it doesnt work

sick birch
#

msg.author == client.user will only work if the person sending the message is the bot itself

#

Should be msg.author != client.user

thorn grove
#

okay

hushed galleon
ivory wraith
#

okay

thorn grove
#

guys

#

need help again

#

i want to ping the author of the message but it only shows the id

indigo pilot
#

Hey! Im back once again haha..
So i have a button, and its not running. I added print("hi") at the start of the code and it dosnt print. No errors

Any ideas?

class UserQuoteButton(discord.ui.Button):
    def __init__(self, channelvar):
        self.channelvar = channelvar
        super().__init__(label='Accept quote', emoji="📡", style=discord.ButtonStyle.green, custom_id='agdczcs')
    async def cazzllbagssdgck(self, interaction: discord.Interaction):
        print("running")```
thorn grove
indigo pilot
# thorn grove

Thats not how u ping someone lol
A) <@{Id}> (bad way}
B) use something like member = get_member() then member.mention

indigo pilot
#

1S

thorn grove
#

how would i put it in my code

indigo pilot
#

Msg.guild.get_member()

thorn grove
#

oh

indigo pilot
#

U need to set it to a var tho

hardy yoke
#

msg.author.mention should work fine without getting

indigo pilot
#

Oo yea ^^

#

That works, but to mention ppl in other things thats how u should do it, the way i said. Unless u can use ctx.author.mention ofc

thorn grove
#

yee it worked

#

tysm guys

indigo pilot
thorn grove
hazy oxide
#

if "bot" in message.content

white aurora
#

@bot.event
if message.content == ‘bot’:
await message.channel.send(‘hello’)

slate swan
#

If my bot is going to be in more than one server, is there anything specifically that was to be different?

sick birch
#

No, just make sure you don't hardcode any IDs or anything like that

slate swan
sick birch
#

Those are context-dependant, so the channel and guild are completely different each time

slate swan
#

Yeah

#

what about tasks?

#

they won't effect anything right

sick birch
#

Nope

dusky pine
slate swan
dusky pine
#

ok then just do what robin said

indigo pilot
sick birch
indigo pilot
#

View is being added fine

sick birch
#

Also the callback has to be called "callback"

#

It also needs to have 3 arguments: self, the interaction, and the button

indigo pilot
#

?
async def callback(self, interaction: discord.Interaction):

#

That?
This cooldown is killing me 😭

sick birch
#
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
  ...

this is an ideal callback

indigo pilot
#

Ohh i never knew that it had to be called that, im dumb

#

" -> None:"
do i reallllly need this? 🙄

slate swan
#

Yes

indigo pilot
#

Mmm

#

Pain, gotta go thru all my views then and add it in

sick birch
#

No but you should always typehint when possible

slate swan
#

^ yes

indigo pilot
#

This bot has been worst then paypal api istg

slate swan
#

pp has an api?

sick birch
#

Well it doesn't need the typehint to be functional. To python, typehints are nothing more than # comments

indigo pilot
slate swan
sick birch
#

!e

def returns_integer() -> int:
  return "This actually returns a string even though the return type is supposed to be an integer"

print(returns_integer())
unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

This actually returns a string even though the return type is supposed to be an integer
slate swan
#

Yeah

indigo pilot
#

I have 0 clue how that works

#

But okay LOL, th anks

slate swan
sick birch
#

It's a recommendation on what the type of certain things should be

slate swan
#

Discord.py commands will always be None though right?

sick birch
#

The computer itself doesn't care about types, in fact, it has no concept of a "type". To it everything is a mess of 1s and 0s, so only statically typed languages will enforce the type

pliant gulch
sick birch
indigo pilot
#

Is it worth swapping to 3.11 yet? Lol

pliant gulch
#

!e ```py
import typing

def foo(bar: str) -> int:
return int(bar)

typing.reveal_type(foo("132"))

unkempt canyonBOT
#

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

Runtime type is 'int'
sick birch
#

You can still return something if you want:

@bot.command()
async def my_command(...):
  return "something" # discord.py doesn't care about this
sick birch
pliant gulch
#

Also new pep draft for typing in 3.12

pliant gulch
#

Just type()

sick birch
#

Conceptually seems familiar, it's able to analyze different things about a function during runtime, like the types of parameters

#

Seems like if you could do that, you should also be able to get the actual return type of a function?

sick birch
unkempt canyonBOT
#

Lib/typing.py line 3351

print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)```
sick birch
#

Oh

pliant gulch
#

!pep 695 Read this pep, def cursed but I kind of like it

unkempt canyonBOT
#
**PEP 695 - Type Parameter Syntax**
Status

Draft

Python-Version

3.12

Created

15-Jun-2022

Type

Standards Track

pliant gulch
#

Look at the spec 100%

indigo pilot
#

!d discord.Guild.get_member

pliant gulch
#

Especially this, very cash money

indigo pilot
#

!d discord.Guild.get_channel

thorn grove
#

guys

#

how can i make it so it sents a message when the blocked text is in a message?

#

i tried putting await msg.channel.send("sus") top of the delete code(line 26) but it didnt work

slate swan
#

if msg.author != client.user is always true?

thorn grove
#

wait

#

i mean yes

slate swan
#

your checking if the message author is not equal to the user?

slate swan
#

that's what != means

thorn grove
#

if the a userr(not the bot) sent a message that is = to blocked(array of strings )

thorn grove
slate swan
#

@thorn grove try this instead.. str(msg.content).lower()

hushed galleon
slate swan
hushed galleon
#

the code would seem to work if the send() came just before deleting the message, assuming it would have reached the delete() line in the first place

slate swan
hushed galleon
slate swan
#

Or it already works.

thorn grove
#

i just want to make it send a message after the deletion

slate swan
#

Oh

hushed galleon
thorn grove
#

doesnt delete the message

hushed galleon
#

was there an error in your console?

thorn grove
#

uhh wait

slate swan
#

Did you remove the await msg.delete() before adding in the channel send

thorn grove
#

i also wanna delete it

thorn grove
slate swan
thorn grove
#

it works now

#

turns out i misspelled something lol

slate swan
#

😭

thorn grove
#

sorry for wasting your time guys 😔

slate swan
#

how can i just get the client_status part from this

thorn grove
#

guys

#

nvm

#

too much questions for one day

#

was gonna ask what is the code on waiting for a certain amount of secs

indigo pilot
#

Hey, anyone got a idea of how i can get all the servers categories,
find a category called something specificly
then set the id of that category to a var. Not sure if theres a method to get all category info in a list but yea

indigo pilot
#

U gotta import a module tho, if ur using pycharm it will tell u what module else i think its called just asyncio

humble otter
#

Whats the best way to send a message into a channel in an on_reaction_add listener?

indigo pilot
#

Or if its the same channel
just reaction.channel.send()

#

Not sure if its called "reaction" but yk what i mean

humble otter
#
@bot.event
async def on_reaction_add(reaction, user):
    if user != bot.user:
        if reaction.message.id in msgs_to_check and str(reaction.emoji) == "ℹ":
            msgs_to_check.remove(reaction.message.id)
            link = re.match(r"https://pcpartpicker\.com/list/([a-zA-Z0-9]+)", reaction.message.content)
            product_info = info(link)
            await reaction.message.channel.send(product_info)@bot.event

#

This is wat I tried

#
 RuntimeWarning: coroutine 'Command.__call__' was never awaited
  await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
#

This was my error

indigo pilot
#

U forgot await, thats what it means

humble otter
slate swan
#

yeah

indigo pilot
humble otter
#

I have an await

slate swan
indigo pilot
#

^

humble otter
#
import requests
from bs4 import BeautifulSoup
import re
import discord
from discord import reaction
from discord.ext import commands


bot = commands.Bot(command_prefix='>')

@bot.event
async def on_ready():
    print('Ready!')


msgs_to_check = []

@bot.event
async def on_message(msg):

    if 'https://pcpartpicker.com/list/' in msg.content:
        await msg.add_reaction("ℹ")
        msgs_to_check.append(msg.id)

@bot.event
async def on_reaction_add(reaction, user):
    if user != bot.user:
        if reaction.message.id in msgs_to_check and str(reaction.emoji) == "ℹ":
            msgs_to_check.remove(reaction.message.id)
            link = re.match(r"https://pcpartpicker\.com/list/([a-zA-Z0-9]+)", reaction.message.content)
            product_info = info(link)
            await reaction.message.channel.send(product_info)

def info(link):
    link = link + "/by_merchant/"
    res1 = requests.get(link)
    soup1 = BeautifulSoup(res1.content, "html.parser")
    res2 = requests.get(link)
    soup2 = BeautifulSoup(res2.content, "html.parser")

    list = ["**Product List**"]

    for names in soup1.find_all("td", class_="td__name"):
        clean_data = (re.sub('<>', '', names.text))
        if clean_data not in list:
            list.append(clean_data)

    for price in soup2.find_all("td", class_="td__price")[-1]:
        list.append("\n**Price**")
        list.append(price)

    for comp in soup2.findAll('div', attrs={"id": "compatibility_notes"}):
        clean_data = (re.sub('<>', '', comp.text))
        ns = clean_data.replace('\n', ' ')
        ns2 = ns.replace('      ', '\n\n')
        ns3 = ns2.replace('   ', '\n\n')

        list.append(ns3)

    list_info = '\n'.join(list)
    return[list_info]


@bot.command()
async def info(ctx, link):
    list_info = info(link)
    await ctx.send(list_info)

#

Here is the whole bot

indigo pilot
humble otter
#

Ok let me try

indigo pilot
#

No

humble otter
#
Ignoring exception in on_reaction_add
Traceback (most recent call last):
  File "C:\Users\Matt\PycharmProjects\nanoreviewbot\venv\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Matt\PycharmProjects\nanoreviewbot\main.py", line 29, in on_reaction_add
    await msgs_to_check.remove(reaction.message.id)
TypeError: object NoneType can't be used in 'await' expression

indigo pilot
#

It wouldnt be thatits a yea

#

Weird

thorn grove
indigo pilot
slate swan
indigo pilot
#

Oh

thorn grove
slate swan
#

use asyncio sleep

#

time.sleep() stops the entire execution of the program. If you just want to delay one async response thread use asyncio.sleep

slate swan
#
import asyncio

await asyncio.sleep(5) # sleep for 5 seconds

@thorn grove

slate swan
indigo pilot
#

I would love to know this skill

slate swan
indigo pilot
#

Lmao

#

Coding = pain

slate swan
#

😭

#

Not for me, some times I do feel like breaking my computer....

indigo pilot
#

Correction
if len(code) > 100.lines:
return(pain)

cold sonnet
#

a 100 lines stops your abilities to have fun??

indigo pilot
#

Ive felt that way all day. Im at 31 views at the moment, and the amount of args i gotta pass thru is killing me

indigo pilot
#

Anything below that is doable

slate swan
#

sad life youre living in

humble otter
#

Any other ideas how to fix my problem?

indigo pilot
#

Im at 600 rn, its killing
20 lines is a command the rest is all views

slate swan
slate swan
indigo pilot
indigo pilot
indigo pilot
# slate swan what are you doing

Ticke tsyetem
You make ticket, req gets sent to artists, if accepted it disables all the buttons of the other quotes or questions

thorn grove
#

btw can i have multiple files for my bot

indigo pilot
#

Sounds simple but im dying

thorn grove
#

multiple python files

slate swan
indigo pilot
#

Also is it just me or does nayone else lay there cogs out one cmd per file

#

Im so used to js, and its so much cleaner

slate swan
thorn grove
indigo pilot
#

*heroku *

thorn grove
#

so i was thinking if adding a new .py file will work

cold sonnet
#

it should be pushed if it's in the branch innit

humble otter
#

Ok did print statement debugging with my code

The problem is this line msgs_to_check.remove(reaction.message.id)

and with that line I get this error

RuntimeWarning: coroutine 'Command.__call__' was never awaited
  await coro(*args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

but when I add an await and make it await msgs_to_check.remove(reaction.message.id) I get

TypeError: object NoneType can't be used in 'await' expression

So I have absolutely no idea what to do

slate swan
#

its a normal function which you called and it returns the result, which is None which ofc you tried to await the result(NoneType) and not a corourine object

humble otter
#

So then how would I fix that?

slate swan
#

you dont await it👁️ 👁️

humble otter
#

But then I get the first error

indigo pilot
#

Nvm just relised as i pasted whta the issue was oops

slate swan
humble otter
#

@slate swan

slate swan
#

just rename the first info function

humble otter
#

Oh

#

that was easy

indigo pilot
slate swan
#

:3

indigo pilot
#
Traceback (most recent call last):
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\kaelm\PycharmProjects\mainbot\cogs\ticket\ticketcore.py", line 507, in callback
    await interaction.channel.edit(category=categorya)
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py", line 371, in edit
    payload = await self._edit(options, reason=reason)
  File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 417, in _edit
    parent_id = parent and parent.id
AttributeError: 'int' object has no attribute 'id'```
#

Im confused as it shouldnt be running that part of the code

slate swan
#

categorry is an int lol

indigo pilot
#

But thats the only thing with id

indigo pilot
#

No ?

#

Categorry is each category, and im trying to just get the id of it

slate swan
#

yeah but it seems like its returning an intpithink

#

OHHH wait

#

im just being dumb

indigo pilot
#

Im still confused why its even running that tho lmfao

slate swan
indigo pilot
#

Oh ncm

ancient jolt
#

im trying to run this code here: https://pastebin.com/bQ92zNFt, but once I run the command $timer 1s in my discord channel i get this error "discord.ext.commands.errors.MissingRequiredArgument: time is a required argument that is missing."

indigo pilot
#

Im dumb it should be running nvm

slate swan
indigo pilot
#

Ohhh

slate swan
#

you need to pass a category object and not an id because it accesses the id internally hence the attribute error, i shouldve read it lol

silk fulcrum
ancient jolt
#

wdym by that? its my first time coding a bot so

cold sonnet
#

he put self even though he shouldn't have

#

remove self from your arguments xen

silk fulcrum
#

ah

cold sonnet
#

you use that in classes only

silk fulcrum
#

yeah

ancient jolt
#

ah okay

indigo pilot
#

I only remember like half of it lol

indigo pilot
#

Wait oh

#

Im dumb holy shet

silk fulcrum
ancient jolt
#

ah

silk fulcrum
#

and this is what you sent

#

if that was your error

slate swan
thorn grove
#

my code doesnt work now

ancient jolt
#

as they had mentioned earlier

thorn grove
#

is it because i used 2 @client
event

silk fulcrum
#

you can create as many events as you want?

#

if they're not same of course

austere vale
#
  @commands.Cog.listener()
  async def on_raw_bulk_message_delete(self, payload):
    length=0
    for message_id in payload:
      length=length+1
    embed=nextcord.Embed(color=0xfd9fa1, title='Bulk Message Delete',timestamp=datetime.datetime.utcnow(),description=f'Channel: <#{payload.channel_id}>\n{length} messages deleted')
    await self.bot.get_channel(933978399280599080).send(embed=embed)

can someone help me? im not sure how to get the number of messages purged

thorn grove
#

the last @client.event only works

slate swan
thorn grove
silk fulcrum
thorn grove
#

github and pydroid

austere vale
thorn grove
#

i used pydroid for that

thorn grove
slate swan
silk fulcrum
austere vale
#

o

silk fulcrum
#

do u know python?

slate swan
silk fulcrum
#

not you

austere vale
#

im a noob with python

slate swan
#

It's okay.

thorn grove
#

i learnt mine in a book

silk fulcrum
#

then probably its early for a bot

thorn grove
#

by hywell carver

silk fulcrum
#

but idk

#

i cannot say anything

slate swan
slate swan
silk fulcrum
#

im just poop

thorn grove
slate swan
silk fulcrum
thorn grove
#

lol that maybe what caused it

slate swan
austere vale
silk fulcrum
slate swan
#

master rejected my offer to be buddies😔

silk fulcrum
#

i didnt get it

slate swan
#

were both poop at python so we are frens

silk fulcrum
#

sorry, i thought it would be better to ignore

slate swan
#

🗿

silk fulcrum
#

oh bruh me dumbass

#

ok i dont mind :)

slate swan
#

fren

#

ImportError: cannot import name 'PartialMessageable' from 'discord.channel'
I've never gotten this, I think it might be because I have pycord and disnake installed too?

silk fulcrum
#

discord.abc

slate swan
#

but I don't even use that?

silk fulcrum
#

if there is a PartialMessageable class

#

then just remove it?

thorn grove
slate swan
silk fulcrum
slate swan
slate swan
silk fulcrum
#

😳

silk fulcrum
thorn grove
#

still doesnt work

slate swan
thorn grove
#

like that?

silk fulcrum
#

async def somename(msg)

slate swan
#

you have to declare the function 😩

thorn grove
#

oh lol

slate swan
#
@client.listen('on_message')
async def SOMENAME(msg) -> None:
   # do stuff
thorn grove
#

im just starting bot developing sorry

silk fulcrum
#

that's basics of python?

thorn grove
slate swan
#

🤷

slate swan
thorn grove
#

whats "SOMENAME"

slate swan
#

its good especially for your linter

slate swan
slate swan
silk fulcrum
thorn grove
slate swan
#

its the instance name pithink

#

when you declare a function you make an instance of it named with the name given uppon the signature

slate swan
#

me neither

thorn grove
slate swan
#

only discord.ext.commands.Bot has the method lol