#discord-bots

1 messages · Page 77 of 1

austere vale
#
  @commands.command()
  async def panel(self, ctx:commands.Context):
    if not ctx.voice_client:
      vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    elif not getattr(ctx.author.voice,'channel',None):
      await ctx.send('Join a voice channel first lol.')
      return
    else:
      vc: wavelink.Player=ctx.voice_client
    if not vc.is_playing():
      await ctx.send('Play something first.')
      return
    embed=nextcord.Embed(title='Music Panel', description= 'Control Runa by clicking on the buttons below.')
    view=ControlPanel(vc, ctx)
    await ctx.send(embed=embed,view=view)
``` could someone help me fix the error please?
slate swan
#

wym

primal token
primal token
austere vale
#

so it should be view=ControlPanel(self)
instead of view=ControlPanel(vc, ctx) ?

primal token
#

?

austere vale
#

i have 2 classes in this cog and i thought that might be whats messing it up, but im not sure

class ControlPanel(nextcord.ui.View):
  def __init(self,vc,ctx):
    super().__init__()
    self.vc=vc
    self.ctx=ctx
#buttons below


class MusicCog(commands.Cog, name='Music'):

  def __init__(self, bot):
    self.bot = bot
primal token
slate swan
#

bruh i didnt even change the code and now the bot responds after like 10 sec

primal token
#

blockingio

crimson plover
#

So obviously this would work as an indentation command await ctx.send('>>> Pong! %sms' %response_time)

But. My question is how would i format the text for something like the formats of
'css
askjdnasjkdn askjdnaskjdn
'

i know obviously thats not the format but wasnt sure how to put it in the code for something that is a single line like that... Sorry I am new to discord Bots and python here.

austere vale
#

ooo thank you

primal token
#

arent those called inline embeds?

silk fulcrum
primal token
#

if youre referring to them ofc

primal token
silk fulcrum
primal token
#

ok

austere vale
#
  @nextcord.ui.button(label='Resume/Pause', style=nextcord.ButtonStyle.blurple)
  async def resume_and_pause(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
    if not interaction.user==self.ctx.author:
      await interaction.response.send_message('You can\'t do that. Run the command yourself to use these buttons.', ephemeral=True)
      return
    for child in self.children:
      child.disabled=False
    if self.vc.is_paused:
      await self.vc.resume()
      await interaction.message.edit(content='Resumed', view=self)
    else:
      await self.vc.pause()
      await interaction.message.edit(content='Paused', 

when i press the resume/pause button while a song is playing, it resumes it instead of pausing it. is there something wrong with my if statement?

#

nvm, i got it!!

crimson plover
#

@silk fulcrum I'm not sure that's why I'm asking

#

And was trying to give an example

#

and @primal token what do you mean by code blocks im sorry

analog aurora
#

hi got problem i have installed python 3.7 and it cant show on cmd

dark jacinth
indigo pilot
#

so yea

#

whats the command to update again maybe i did it wrong

#

as i havnt used python in a good while

slate swan
#

Any idea why this isnt working ?

modList = [394506589350002688, 697725862128386048] # just some ids as examples

def check_Mod(ctx):
    if ctx.author.id in modList:
        return ctx.author.id in modList

@commands.command()
@commands.check(check_Mod)
async def test(ctx):
    await ctx.send("You are a mod!")

saying test isnt a command

sick birch
sick birch
#

If your interaction object was interaction, you would do interaction.delete_original_response() and not interaction.response.delete_original_response()

indigo pilot
#

yea that dosnt work etiehrthought i said that

#

lol

sick birch
#

What error do you get when you try interaction.delete_original_response()?

indigo pilot
#

let me see lul

indigo pilot
sick birch
#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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

Deletes the original interaction response message.

This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
slate swan
#

evening all, I was wondering if any could advise what I should be looking into when I want to lock a reaction role down to the message posted, so im not picking up roles on any message I may use these selected emojis. I seen Rapportz example where it requires a message ID but is there a way to do it without a message ID? Do i need to look for the guild id, get the channel and then use that channel to fetch the payload message?

indigo pilot
#

but it wont work

sick birch
#

It was renamed a while ago so make sure you update

indigo pilot
#

do i just pip install then

#

or is there a cmd

#

wait no i did do it right

#

weird

#

fixed it it was delete_original_message but that still dosnt work for me lol

atomic glacier
#

    if scope == 'all':
        guild = ctx.guild
        members = guild.members
        print(members)
        print(len(members), members)
        for x in members:
            print(x)
            await x.add_roles(role, reason=None, atomic=True)

#

its only printing the bot

dry kelp
#

Hey hey... how could i make a monthly payment thing? I have 0 knowledge into this and honestly i don't even know what to start with

dry kelp
#

stripe requires a credit card

sick birch
dry kelp
#

or bank IBAN if im not wrong... im still a minor

#

what do u think of paypal?

atomic glacier
sick birch
#

Otherwise I’d just forget it

dry kelp
#

but i still need something till then

#

do u think paypal is a good solution?

sick birch
#

Probably not

#

If a bot wanted me to make payments through PayPal i better be ready to say bye bye to the money

dry kelp
#

why?

#

paypal preferes USD

#

low taxes using that

sick birch
#

Not really secure for business transactions

#

What’s stopping me from running away with your money?

dry kelp
#

How could you even do that?

sick birch
#

Just not provide them the service you say you will

dry kelp
#

Sorry im getting confused right now

#

so it's because of a low security? is that what u mean?

#

i didn't get the part where u said "running away with your money"

sick birch
#

Say you ask your users to pay you $5 for a bot function

#

They pay you

dry kelp
#

yes

sick birch
#

What’s stopping you from not giving them that bot function

#

Your users can’t be certain of that

dry kelp
#

Why would i do that?

#

also i want to make it automatically...

#

no need for me to manage that

sick birch
#

Don’t know if you can do it automatically

sick birch
dry kelp
#

Ok so lemme tell u what im currently up to do

#

its a NSFW monthly subscription

#

that way we can avoid some minors from seeing it.. im also a minor but meh

dry kelp
#

like what i have to do is to somehow pull the user ID then add it to a db

#

if the user id is there then let the user use the NSFW commands...

#

@sick birch Yes looked into it. to allow payments they asking for the IBAN

dry kelp
slate swan
#

How would i invaildate said key ?

@bot.command()
async def redeem(ctx, key):
    query.execute("""SELECT CLAIMED_KEY FROM KEYS WHERE USER_ID = ?""",(ctx.author.id,))
    list_keys = [row[0] for row in query.fetchall()]
    if key in list_keys:
        await ctx.send('vaild key ')
        # Invaildate said key
    else:
        await ctx.send('invaild key ')

something like this ?

#

im using sqlite3

#

nvm fixed by my self ^

atomic glacier
#

How would one recommend I save a string set with a command (unique to each server)

#

I was thinking SQL data store with firebase

sick birch
#

I'd create a website using discord Oauth and integrate it with Stripe

#

Once a user successfully does a transaction, I can add their ID (through oauth) to a database

#

The discord bot also has access to this database, so it can verify the premium status of users

supple coral
#

hey i wanted to make that the bot updates the slash commands but every time this Message comes:

KeyError: '1016801750214246472' ```
naive briar
wicked kayak
#

how install pycord i forgot the command

#

@sick birch

naive briar
slate swan
#

Guys how do I get the player's name from ctx

#

!discord.Context.ctx

primal token
unkempt canyonBOT
primal token
unkempt canyonBOT
slate swan
#

thanks

#
import requests
import discord, time
import random, threading
import asyncio
from discord.ext import commands

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

@bot.command()
async def crash(ctx):
    ok = await ctx.send('**Checking api , Please wait**')
    game = requests.get("https://rest-bf.blox.land/games/crash").json()
    def lol():
        r=requests.get("https://rest-bf.blox.land/games/crash").json()["history"]
        yield [r[0]["crashPoint"], [float(crashpoint["crashPoint"]) for crashpoint in r[-2:]]]
    for game in lol():
        games = game[1]
        lastgame = game[0]
        avg = sum(games)/len(games)
        chance = 1
        for game in games:
            chance = chance = 95/game
            prediction = (1/(1-(chance))+avg)/2
            if float(prediction) > 2:
                color = 0x81fe8f
            else:
                color = 0xfe8181
            desc = f"""
        **Crashpoint:**
        {prediction:.2f}x
        **Chance:**
        {chance:.2f}%
        """
                
            em=discord.Embed(title="DEMON V2",description=desc,color=10428871)
            em.set_thumbnail(url="https://i.imgur.com/axLm3p6.jpeg")
            await ok.edit(embed=em)

I get keeping like this error idk what wrong w/ it , somtimes it works , sometimes it doesnt

#

^ error log

#

i feel like this is an easy fix but i cant see it

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

supple coral
primal token
#

And it seems like it didnt return valid JSON

naive briar
primal token
#

?

rare echo
#

dictionary = no word

#

or number…

naive briar
primal token
#

poor choice of words

naive briar
#

I'm suck at explaining things

slate swan
#

well more like it just takes a long time to load

cursive nova
#

how can i make this send in blocks instead of sending line by line
''' file = open("medivia.txt")
lines = specified_lines = [0, 1, 2, 6, 7, 8]
print("Sending lines")
for pos, l_num in enumerate(file):
if pos in specified_lines:
print(l_num)
await ctx.send(l_num)
await ctx.send("----------")'''

mossy jacinth
#

Got two things to fix...

First: TypeError: abc.send123() missing 2 required positional arguments: 'self' and 'ctx'
Second: It always creates a new channel with the same name when using the command to load the cog...

hazy isle
#

Hello, I was wondering if anyone would be able to speak to me about sending messages through the webhook via python script. I posted about it in a help channel and was referred to here. Please reply to this message if so. Thank you!

Please refer to #help-bread

I am rather new to python as well, I apologize in advance.

hazy isle
torn sail
hazy isle
#
from discord import Webhook
import aiohttp
import asyncio

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('https://discord.com/api/webhooks/xxxxxxxxxxxxxxx/i5957RCj2umzw5W9QFw-ZaaUEY8YlpCGtSOoQcxZSuLnICzZGvvTjTUDHAbQa5rygECa', session=session)
        await webhook.send('Hello World', username='foo')

asyncio.run(foo())
torn sail
#

!d discord.Webhook.from_url

unkempt canyonBOT
#

classmethod from_url(url, *, session, bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") from a webhook URL.

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

huh

hazy isle
#

?

torn sail
#

oh yeah then @hazy isle if your on 1.7.3 you pass the adapter kwarg instead of session

torn sail
primal token
#

no

torn sail
#

yes

sick birch
#

yr'oue*

hazy isle
#

await request(verb, url, payload=None, multipart=None, *, files=None, reason=None)

so use this?

#

await

primal token
hazy isle
primal token
#

Well, if i continue to explain i doubt you will get the terms or how it would work as this is basic python OOP and understanding would be a disaster if you havent studied about the paradigm or how python uses it

hazy isle
#

Well, at least we are on the same page. stressed

primal token
#

I would recommend learning, Basic python if you haven't, python's OOP and then asynchronous programming and its implementation in python, over causing unnecessary headaches to yourself

hazy isle
#

Okay, back to the books I go. Thanks for the attempt to help then. I appreciate it.

I have just started messing with python scripts being used with discord.

This appeared to be rather simple, but the wall I hit with this simple test of sending messages to discord really just grinded my gears. In the help channel, they said it appeared I was trying to mix to different style of it together. I think I am just trying to make it work based off of what I can read. lol

hazy isle
primal token
hazy isle
primal token
#

np!

pulsar bay
#

bots create they’re own role upon joining servers right?

primal token
#

An Integration role, yes.

oblique loom
hazy isle
#

Also, he was the first video I spent time on. Great vids.

#

The 1 hour video. blobsweat

oblique loom
#

Yes he has great tutorials. Respect

oblique loom
hazy isle
#

Like I am pulling this from discord.py/readthedocs.io

from discord import Webhook
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', session=session)
        await webhook.send('Hello World', username='Foo')
oblique loom
hazy isle
#

lol so that's what is more frustrating.

oblique loom
#

Closer to beginner for me

hazy isle
#

Same. We would be the blind leading the blind.

oblique loom
#

So far all I’ve done is make a auto bridge thing for Minecraft (I don’t use it) and I also made a T-Rex run game cheat

hazy isle
#

I comprehend the formatting. This is my first experience with async. So that's that.

#

I made a script that counts cards for you in black jack. (no I don't use it, it was just to test my understanding.)

oblique loom
#

Nice

hazy isle
#

It has a fancy menu in it as well. lol

#

While loops took me forever and a day (maybe 2 full days) to learn.

oblique loom
#

So far I’m just using my coding skills that I have right now, and making bigger things, and maybe finding out more and more by scrolling through this discord and sometimes asking questions

sick birch
oblique loom
#

I’m good with while true loops, that like 20% of the 2 projects I have made so far.

#

Idk if you guys mean more complex loops tho

hazy isle
#

For me though, it is extremely difficult to really spend a good amount of time in it as I have a full time job that is not related to coding at all and small family unit. lol so I really can only mess with this stuff in the evenings. Maybe get 2-4 hours in here and there.

oblique loom
#

That’s a good schedule. If keep that up for a while, you could learn a lot pretty quick.

sick birch
primal token
slate swan
oblique loom
slate swan
#

For me , thats what really spark my coding , i took a java class and it really help me understand the fundamentals of coding

hazy isle
# slate swan You should get into classes if your really passionate abt coding , only a 1hr a ...

I've contemplated it. Harvard actually offers a free python class I have been playing with the idea.

Also, like this makes no sense to me, thus far. I pulled this right from discord.py

import requests
from discord import Webhook, RequestsWebhookAdapter

webhook = Webhook.partial(123456, 'abcdefg', adapter=RequestsWebhookAdapter())
webhook.send('Hello World', username='Foo')

Obviously I filled it in with the correct things on my end, but when I run it from cmd it just sits there forever. The message never goes through to the discord. lol like WHY?! why

primal token
primal token
#

ok

oblique loom
#

I mean I’m a beginner myself. And I used his hour long tutorial and though it was pretty good, but at the same time more advanced programmers would realize more how much they really teach and what they miss out.

slate swan
hazy isle
primal token
sick birch
hazy isle
primal token
sick birch
oblique loom
sick birch
unkempt canyonBOT
#
Resources

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

sick birch
#

@hazy isle you might be looking at an older version of the docs, this is what I'm seeing from the docs:

from discord import Webhook
import aiohttp

async def foo():
    async with aiohttp.ClientSession() as session:
        webhook = Webhook.from_url('url-here', session=session)
        await webhook.send('Hello World', username='Foo')
hazy isle
#

Oh my god, I am sorry. I sent the wrong one. I found that other snippet in the discord.py

#

I've tried both what you posted and the other one I found.

sick birch
#

The other one you found seems to be from an older version

hazy isle
#

I set it up with the URL and just test what they have there. It just sits on the screen.

#

the cursor just blinks.

sick birch
#

Did you use asyncio.run() to kickstart the event loop?

hazy isle
#

At the end of it, yes.

sick birch
#

Hm. You're sure you're running the right file?

sick birch
hazy isle
#

One moment.

oblique loom
primal token
#

np

sick birch
#

Do me a favour, try printing discord.__version__ to see what version you're on

hazy isle
#

I already had it open on the discord API wrapper.

__author__ = 'Rapptz'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015-present Rapptz'
__version__ = '1.7.3'```
#

you are amazing.

#

It's out of date.

#

I just updated it through pip now.

pikafacepalm

#

I am on 2.0.1 now....let's try this again. lol

#

IT WORKED! stressed

Thank you so much.

notes

Check to make sure all packages are up to date.

#

This is how I learn best. Making mistakes!

static garden
#

I have an issue here. I don't understand how logging works apparently. On this example I get the logs to appear in the discord.log file but not on the console. How can I make it appear as well on the console?

    log_handler = logging.handlers.RotatingFileHandler(
        filename='discord.log',
        encoding='utf-8',
        maxBytes=5 * 1024 * 1024,  # 5 MBs
        backupCount=3)  # Rotate through 3 files
    bot.run(
        token=hellodiscordiamnotthatdumbxD,
        log_handler=log_handler,
        log_level=logging.INFO)
```Then inside a cog:
```py
    logger = logging.getLogger('discord')
    logger.info("test to see if this works")
```What am I missing?
paper sluice
#

!d logging.StreamHandler

unkempt canyonBOT
#

class logging.StreamHandler(stream=None)```
Returns a new instance of the [`StreamHandler`](https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler "logging.StreamHandler") class. If *stream* is specified, the instance will use it for logging output; otherwise, *sys.stderr* will be used.
paper sluice
#

make an instance of that ^ and it to your logger.

static garden
#

thanks

jagged adder
#

im trying to use a def func to provide default values for my bot.command cmd;
the problem is that if i put it above the bot call and define the returned value, its random variables r locked when the bot is started up.
how can i get around this ?
(this is a simplified example below)

def fruit():
  fr = random.choice(['apple', 'banana'])
  ch = random.choice(['1', '2'])
  return fr, ch
fr, ch = fruit()

@bot.command(name='fruit')
async def selection(ctx, fruit=fr, num=ch):
  ctx.send(fruit, num)
#

atm, itll just print the same thing repeatedly, as fr/ch is locked when the bot is launched

naive briar
slate swan
#

I'm working with the guilded.py, but it seems to be based from the discord.py so why am I getting this error?
Context: I'm trying to change the name of the bot when it talks in chat

maiden fable
#

This channel is for help with discord bots, not guilded bots. You might wanna open a help channel, but seeing the error, it seems like you can't edit bot details from code

slate swan
#

Ok

jagged adder
maiden fable
#

Thanks!

meager chasm
#

i don't (🤢)

ashen perch
#
@tree.command(guild = discord.Object(id=test_server_id), name = 'start_game', description='Choose a game') 
async def slash2(interaction: discord.Interaction, option: game):
    await interaction.response.send_message(f"Command response {option}", ephemeral = True) 

how do i pass a list as a parameter in a slash command game is a list i made

naive briar
#

But I'm assuming you want to add a parameter option that gonna take the arguments as a list

vale wing
naive briar
unkempt canyonBOT
#

examples/basic_bot.py line 44

@bot.command(description='For when you wanna settle the score some other way')```
shrewd apex
#

u can make a custom convertor

naive briar
#

:thonk:

shrewd apex
#

that basically make tuple of the strings u input by splitting at space

vale wing
#

You might also mean autocomplete

shrewd apex
#

it depends on his use case

ionic edge
#
        shrike = self.client.get_user(923963169653784606)
        embed = discord.Embed(
            description=f"[**Official Discord Server**]",
            color=0x9C84EF
        )
        embed.set_author(
            name="shr!ke#0420",url= shrike.avatar.url```
#

set author url not working brother

naive briar
ionic edge
#

i had to use icon_url

naive briar
#

Nice 👍

slate swan
#

Alright, so I have this view, ```py
class ticket_panel(discord.ui.View):
def init(self, bot):
super().init(timeout = None)
print("0")
self.bot = bot

@discord.ui.select(
    placeholder="Choose a ticket type...",
    min_values = 1,
    max_values = 1,
    custom_id = "tickets",
    options = [
    discord.SelectOption(label = "Bot Development", emoji = ":bot:"),
    discord.SelectOption(label = "Graphic Effects", emoji = ":gfx:"),
    discord.SelectOption(label = "Server Creation", emoji = ":server:"),
    discord.SelectOption(label = "Visual Effects", emoji = ":vfx:"),
    discord.SelectOption(label = "Marketing", emoji = ":marketing:")])
async def ticket(self, select: discord.ui.Select, interaction: discord.Interaction):
    member = interaction.user

and when I call it, it doesn't print 0 or b, only a, why? no erros btwpy
print("a")
view = ticket_panel(self.bot)
print("b")

naive briar
#

Eh

#

Is there anything below member = interaction.user?

paper sluice
paper sluice
#
print("a")
view = ticket_panel(self.bot)
print("b")
vale frigate
#

ah guys how kick some one from a server?

ionic edge
#

discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'afk' raised an exception: TypeError: execute expected at most 2 arguments, got 3

slate swan
naive briar
#

!d discord.ext.commands.Greedy

unkempt canyonBOT
#

class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
naive briar
#

Wait

jagged adder
#

how do i delete a discord msg by reacting to it with a specific emoji?

naive briar
#

My bad

#

But I think you still can use converter

vocal snow
unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
vocal snow
#

payload is an instance of discord.RawReactionActionEvent. it likely has an emoji attr which you can use to check the emoji

naive briar
naive briar
unkempt canyonBOT
#

examples/app_commands/transformers.py line 87

async def shop(interaction: discord.Interaction, action: Literal['Buy', 'Sell'], item: str):```
ashen perch
#

thanks for the help ill try it later

vale frigate
#

why it send me this error AttributeError: 'Interaction' object has no attribute 'joined_at' code py embed.add_field(name=f'Who Report User Join Time:', value=f"{interaction.joined_at.strftime('%h, %a, %#d %B %Y')}", inline=True)

hardy yoke
vale frigate
#

ok

ionic edge
#
    @commands.hybrid_command(
        name="afk",
        description="Set your status to AFK.")
    @checks.not_blacklisted()
    async def afk(self, context: Context, reason: str = None) -> None:
        """
        Set your status to AFK.
        
        :param context: The hybrid command context.
        :param reason: The reason for being AFK.
        """
        member= context.author
        if reason is None:
            reason = "No reason provided."
        await self.client.db.execute("INSERT INTO afk (user_id, reason) VALUES ($1, $2)", context.author.id, reason)
        await context.author.id.edit(nick=f"[AFK] {context.author.display_name}")
        await context.send(f"**{member.name}#{member.discriminator}**, You are now AFK : {reason}")```
#

discord.ext.commands.errors.HybridCommandError: Hybrid command raised an error: Command 'afk' raised an exception: TypeError: execute expected at most 2 arguments, got 3

slate swan
#

For some reason when I call my function, everything stops.```py
class ticket_panel(discord.ui.View):
def init(self, the_bot):
super().init(timeout = None)
print("0")
self.the_bot = the_bot

@discord.ui.select(
    placeholder="Choose a ticket type...",
    min_values = 1,
    max_values = 1,
    custom_id = "tickets",
    options = [
    discord.SelectOption(label = "Bot Development", emoji = ":bot:"),
    discord.SelectOption(label = "Graphic Effects", emoji = ":gfx:"),
    discord.SelectOption(label = "Server Creation", emoji = ":server:"),
    discord.SelectOption(label = "Visual Effects", emoji = ":vfx:"),
    discord.SelectOption(label = "Marketing", emoji = ":marketing:")])
async def ticket(self, select: discord.ui.Select, interaction: discord.Interaction):
    member = interaction.user
    channel = interaction.channel
    print("1")
    async with self.the_bot.db.acquire() as con:
        print("2")
        async with con.cursor() as c:
            print("3")
            await c.execute("SELECT * FROM Tickets WHERE memberid = %s", (member.id,))
            print("4")
#

It doesn't even print 0.

vale frigate
#

why this not working
{('%a, %#d %B %Y')}

slate swan
vale frigate
#

ah

#

say the time of rn

slate swan
#

Then just do await ctx.send(datetime.now())

vale frigate
#

ah

#

Ok then datetime.now() Thank You!!

slate swan
#

datetime.datetime.now()

vale frigate
#

um

slate swan
#

You need to install it pip install datetime and import datetime.

vale frigate
#

import it?

#

ok

#

this not wokring embed.add_field(name=f'Time', value=f"{datetime.datetime.now()}", inline=True)

#

no error but it not show

#

@slate swan

naive briar
#

!d discord.Interaction.user

unkempt canyonBOT
vale frigate
#

Ok!!

silk fulcrum
unkempt canyonBOT
#

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

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

New in version 2.0.
silk fulcrum
unkempt canyonBOT
#

discord/utils.py line 737

return datetime.datetime.now(datetime.timezone.utc)```
vital drift
#

I'm trying to make a guard bot with discord.py and there is a place where I'm stuck. How can I reinstate the updated value on channel and role updates?

primal token
#

not a library, its a stdlib

vale frigate
#

ah why this not work py if self.name2.value content "https://discord.com/channels":

paper sluice
#

what are you trying to do?

vale frigate
#

ah

#

check if self.name2.value contents "https://discord.com/channels"

paper sluice
#

do you mean, contains?

vale frigate
#

yees

paper sluice
#

!e you can do something like this

string = 'hello'
if 'h' in string:
    print('yes')
unkempt canyonBOT
#

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

yes
vale frigate
#

OOOh in

rare echo
#

the single word “contents” completely made my brain go numb to everything else in the question trying to figure out what that was

vale frigate
paper sluice
#

not in

vale frigate
#

:0 what a smart guy

rare echo
#

lmao

vale frigate
#

are you sure this should work? if self.name2.value not in "https://discord.com/channels":

#

when i put message link like [#discord-bots message](/guild/267624335836053506/channel/343944376055103488/) it say you can't

#

and it should can bc this in the self.name2.value

#

OHHH

#

sorry me dumb 🙂

#

Thank You for your time!!

vital drift
#

I'm trying to make a guard bot with discord.py and there is a place where I'm stuck. How can I reinstate the updated value on channel and role updates?

cursive nova
#

hello how can i send multiple strings in a codeblock to discord through bot
tried different things it just types the string names.

vale frigate
#

why if "https://discord.com/channels" or " " not in self.name2.value: not working

#

or " " isn't working

primal token
#

!or

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
vale frigate
#

oh

#

Ok!

#

@primal token what this code do if self.name2.value is set:

slate swan
primal token
naive briar
slate swan
naive briar
# slate swan wdym?

I see that you're putting self and d in the call

view = ticket_panel(self, self.bot, "d")

But your view only take 1 argument

slate swan
#

Yeah, I tried to see if it would give an error. For some reason it didn't.

naive briar
#

Hm

slate swan
#

It doesn't work with 1 argument either.

#

The thing is that it worked before, then I changed database and now it isn't working. Even tho I'm not using the database in that command.

slate swan
#

In a slash command, it executes everything until the call, then it quits without an error and all the code below stays un-executed.

#

Found the problem

#

I accidently overwrote the function by assigning a variable with the same name. 🤦‍♂️

naive briar
#

👍

gusty shard
#
@bot.command()
@commands.has_permissions(manage_roles=True)
async def mute(message, member: discord.Member, sure:str):
    role = discord.utils.get(member.guild.roles, name='Muted')
    await member.add_roles(member, role)
    embed=discord.Embed(title=f"{member.name} muted", color=0xff00f6)
    await message.send(embed=embed)
    await asyncio.sleep(sure)
    await member.remove_roles(role)```
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10011): Unknown Role

#

there is a role named Muted and its not above the bots role

#

can somebody help me?

hushed galleon
#

add_roles() doesnt take a member object

gusty shard
#

so i need to remove member before role

#

thank you

hushed galleon
#

mhm

gusty shard
#

(sorry for ping)

#

is there something wrong with await member.remove_roles(role)?

hushed galleon
#

hm im sure that sure should probably be typed with int/float since you're passing it to asyncio.sleep()

gusty shard
#

await asyncio.sleep(int(sure))

#

would that work?

hushed galleon
#

i mean, sure, but you already have it as a command parameter, just replace the typehint and let dpy convert it for you

gusty shard
#

right

#

thank you again

faint sapphire
#

howdy, i use my raspberry pi 3 to host a discord bot, i also plan on hosting a website with it
i was wondering if getting an external ssd for it would be beneficial, it would run on it instead of the micro sd card

slate swan
#

this...isn't the correct channel?

sick birch
#

And considerations like a database

vocal plover
#

And possibly reliability, storing frequently read and written data on an SD card is more likely to result in data loss than something like an external drive designed for that sort of operation, but on the flip side, good backups should remove this from being any more of a problem than needing a new SD card

slate swan
#

yep

#

I can't use the setup_hook 'cause no and syncing inside the method I use Bot.start in, results in a missing app id error

paper sluice
#

Bot.login maybe

#

or connect

slate swan
#

should I connect and login manually

paper sluice
#

yea, idk why you can't use setup hooks but, setup_hook is called in login so you might as well

glad cradle
#

you could do something similar to setup_hook subclassing commands.Bot and overwriting the start method (make call to your setup_hook function and then call the original start method with super().start(...))

unkempt canyonBOT
#

bot.py lines 66 to 76

async def start(self, *, reconnect: Optional[bool] = True) -> None:
    logging.info(f'Starting the bot at {datetime.utcnow()}')

    # This function is similar to a Setup_hook function
    # Load an setup here database connections etc...
    self.load_exts()
    await self.load_json_info()
    self.uptime_start: datetime = datetime.utcnow()
    self.add_persistent_views()

    await super().start(self.TOKEN, reconnect=reconnect)```
light jungle
#

hello everyone, I have a question how to do so that after the bot sent a message and you answered it through the "reply" button, I sent the following message, and when I just wrote without the "Reply" button, I did not answer anything

primal token
#

you can use asyncio.create_task, but why not use setup_hook?

slate swan
#

'cause no

primal token
#

?

glad cradle
#

she's creative

primal token
slate swan
#

jeez im dumb

#

no actually im not

glad cradle
slate swan
#

the copy function for embeds is kinda useful in dpy

unkempt canyonBOT
#

typing.Optional```
Optional type.

`Optional[X]` is equivalent to `X | None` (or `Union[X, None]`).

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the `Optional` qualifier on its type annotation just because it is optional. For example:

```py
def foo(arg: int = 0) -> None:
    ...
```  On the other hand, if an explicit value of `None` is allowed, the use of `Optional` is appropriate, whether the argument is optional or not. For example...
slate swan
#

read the paragraph in the middle

#

!d discord.Embed.copy

unkempt canyonBOT
glad cradle
#

but mypy doesn't cry about it

slate swan
#

so useful ngl

slate swan
#

and its set to a bool, so why would it have an issue

slate swan
glad cradle
slate swan
#

your mypy is drunk

def foo(x: int): ...
def bar(x: int | None = 69): foo(x)
shrewd apex
#

iirc mypy has some implicit and explicit optional config method use that

slate swan
light jungle
shrewd apex
#

ur explanation is sorta confoosing

dull terrace
#

Yeah, sorry, what did you mean froggy_chill

light jungle
shrewd apex
#

!d discord.Message.reference

slate swan
#

after switching from Windows to Mac, i've been getting an error where, when i interact with a button, i get an error. I have no clue how to fix it..

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 1058, in on_interaction
    await self.process_application_commands(interaction)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 722, in process_application_commands
    ) and isinstance(interaction.data, interactions.ComponentInteractionData):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/typing.py", line 2385, in __subclasscheck__
    raise TypeError('TypedDict does not support instance and class checks')
TypeError: TypedDict does not support instance and class checks```
unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

shrewd apex
#

if this is not None it means it was a reply

weary flume
#

still new to python

@client.command()
async def redeem(ctx, message:str):
    tokens = {
        "TIUiPjep4t",
        "bkAZQoZlTc",
        "rRLQJ9oKVz",
    }
    if tokens in message:
        await ctx.send("token found")
    else:
        await ctx.send('Token not found')
dull terrace
#

discord is frustrating me with their buttons

#

you can put 5 emoji buttons in a row but ofc it cuts off at 4 on mobile

#

got too many rows already

radiant parrot
#

how do i grab the username of user who sent message in a channel?

paper sluice
radiant parrot
#

im grabbing the message content

#

but yes on_message event

paper sluice
#

message.author

radiant parrot
#

lovely thank you 🙂

steep estuary
#
discord.player: ffmpeg process 44 successfully terminated with return code of -11.
#

how to fix this irritating error

steep estuary
#

how to add this ?

#

and what is this ?

#

do you mean slash commands?

#

i added that

sick birch
#

Are they global, and are they synced?

steep estuary
#

it is working in my testing server of slashcommands

#

but the slash commands are not appearing in other servers

steep estuary
#

i synced that

#

global ?

#

oh how to globally sync them ?

#

aah that's why they are not appearing in other servers

#

ok

#

wait sharing my code

radiant parrot
#

how would i put current time in embed footer? 🙂

steep estuary
#
await bot.tree.sync(guild=discord.Object(id=936466653271691265))
    print("Synced")
#

i am syncing like this

#

what to change here?

steep estuary
steep estuary
# sick birch `await bot.tree.sync()`
@bot.hybrid_command(name="ban", with_app_command=True, description="Ban a Member from this Server")
@app_commands.guilds(discord.Object(id=936466653271691265))
@commands.has_permissions(ban_members=True)
async def ban(ctx):
  pass
#

this too ?

sick birch
#

yes i believe so

unkempt canyonBOT
#

class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
steep estuary
#

should i remove that guilds line ?

primal token
#

Not exactly

#

they should be instant uppon syncing/registering now

steep estuary
primal token
#

They should, yes

hushed galleon
#

iirc the "try my commands" part is for verified bots only

#

discord lists them based on popularity

steep estuary
#

my bot is verified

sick birch
#

!e

my_tup = ("hello", "world", "element 3", )
print(my_tup[10])
unkempt canyonBOT
#

@sick birch :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | IndexError: tuple index out of range
slate swan
#

@sick birch ever since setting up your Mac have you ever gotten a TypedDict error?

dull knot
#

Guys, say, if I wanted to import a variable from one file to the other, what should I do?
from file import file.variablename?

slate swan
#

you are trying to access item from tuple that doesnt exist

paper sluice
#

!e

print(int('hello'))
unkempt canyonBOT
#

@paper sluice :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | ValueError: invalid literal for int() with base 10: 'hello'
weary flume
#

how do i make my bot read a text file and say whats in it?

paper sluice
#

you should know that.

dull knot
# dull knot Guys, say, if I wanted to import a variable from one file to the other, what sho...

Pretty vague question so lemme rephrase.
I want to

    """         Topic         """  
    @commands.command(name="topic")
    async def topic(self, ctx):
      Responses = Very Long List of Topics
      embed = disnake.Embed(title="", description=f":BA: {random.choice(Responses)}", colour = disnake.Colour.random())
      embed.set_author(name=f"Requested by {ctx.author.nick}", icon_url=f"{ctx.author.display_avatar}")
      
      await ctx.send(embed=embed)
      await ctx.message.delete()

Instead of putting the Responses in the Current file, I want to transfer a variable from a different file to this cmd right here. I tried
from file import file.variablename but it just said these (Picture)

dull knot
#

Aight lemmet ry

paper sluice
#

rip

dull knot
paper sluice
#

nope, these are basic things you should know by now, but you don't because every time someone tries to help you by sending you to docs or a tutorial , you simply ignore it and ask people to write code for you.

dull knot
#

Is there a way to access variables from files which are inside a folder with a hyphen? Tried doing it like this From File-Name.Variable import Responses but it didn't work lol

Asking this just out of curiosity

#

Seems like it works if I remove the hyphen

paper sluice
#

like, from folder.file import object

dull knot
#

yup

#

But instead, the folder has a hyphen in between. Like folder-name.filename

paper sluice
#

then you can't do that

#

the folder name must follow the same rules as naming a variable or function

dull knot
#

so _

paper sluice
#

yea

dull knot
#

lol. Gothchu

silk fulcrum
unkempt canyonBOT
weary flume
#

ty

sick birch
#

Would someone be able to point me to how discord.py handles events internally? I'm mostly interested in what happens starting from when the gateway dispatches, for example, a MESSAGE_CREATE event to you

unkempt canyonBOT
#

discord/client.py line 429

def dispatch(self, event: str, /, *args: Any, **kwargs: Any) -> None:```
primal token
#

which that method uses

unkempt canyonBOT
#

discord/client.py line 418

def _schedule_event(```
feral frost
#

hey guys vs code acting weird. i import smth from my own file and it works but now i import the same thing just with another name and it wont work

#

can i have some help pls

#

nvm i forgot to save it lol

feral frost
#

ye like this

test = "test" test2 = "test"

#

but i forgot that you need to click ctrl + s in vs

primal token
feral frost
#

bruh nvm guys i was just wondering why but i found it

#

i forgot to SAVE it

#

because i use VISUAL STUDIO

primal token
#

autosave is a feature

feral frost
#

well i didnt know

#

i also wont use it

paper sluice
primal token
paper sluice
#

and you can't survive without it

weary flume
#
@client.command()
async def redeem(ctx, message:str):
    tokens = [ "TIUiPjep4t", "PtBVrRBVWv", "7Nkpp9IIpn", "oDM62ZQXsF", "RrSnyx9aXU"]
    if tokens in message:
        await ctx.reply(f"`{tokens}` is now redeemed.", mention_author=False)
    else:
        await ctx.reply('Token not found')
#

not sure why this isnt working

paper sluice
#

you are trying to check if a list in the string

#

which is obv not correct

weary flume
#

still new to python

paper sluice
#

i think you want to iterate over the list, and check if the item of the list is in the string

maiden fable
paper sluice
#

or that

weary flume
#

ok

maiden fable
#

I like the dialogue "I am new to Python" idk why

primal token
weary flume
primal token
#

Thats like saying, I did my own heart surgery because i needed it

maiden fable
#

Nice

meager chasm
#

i love doing my own heart surgery

weary flume
#

fr

meager chasm
#

The tapeworms are so cute ☺️

primal token
#

How does that have any relation to your heart

weary flume
#

yeah now it works but

#

it responds back with the whole thing

meager chasm
weary flume
#

['TIUiPjep4t', 'PtBVrRBVWv', '7Nkpp9IIpn', 'oDM62ZQXsF', 'RrSnyx9aXU'] is now redeemed.

#

thats what it says

meager chasm
#

Yea because that's what you're telling it to send

weary flume
#

what should i change

meager chasm
#

What do you want to send

weary flume
#

the command will go

#

.redeem TIUiPjep4t

#

then it will say the token is redeemed

meager chasm
#

So which variable is storing the token

weary flume
#

tokens

meager chasm
#

No, tokens is storing all the valid tokens

#

Which variable is storing the token given by the user

#

Which is what you want to send

dark pine
#

hello

#

i joined the server to get help figuring out what wrong i have done on my discord bot code

#

if anyone could help me

sick birch
#

Ask away

dark pine
#

i have everything setup, but im still getting error messages for every command i use

#

i have went back through all the code for like 11 times and i cant find what wrong i have done

sick birch
#

Would be helpful to see the error message

dark pine
#

its my first day coding in here

sick birch
#

Jumping into discord.py is probably not a good idea then

primal token
dark pine
#

uhm

primal token
#

material

weary flume
dark pine
#

im not really new to python

#

like i took the class on my first sem this year on college

primal token
#

then skip the step!

dark pine
#

im already used to it

wheat urchin
#

Hello

dark pine
#

but its my first day coding a discord bot

sick birch
dark pine
#

i just wanted to code a bot that counts a virtual points

#

with add, remove and balance command, and it felt like it would be normal

#

but its not, using too many external functions

#

would you like to see what doesnt work ?

sick birch
#

How else could I help lol

meager chasm
#

Psychokinesis

dark pine
#

im using replit btw

#

not sure if the issue is from the cloud thing

sick birch
#

I have a feeling I know where this is going

dark pine
#

but it works fine runnning it on cloud

sick birch
#

Send the error please

#

Otherwise it’s impossible to tell what’s wrong (though I have a hunch)

meager chasm
#

inb4 json

sick birch
#

I unfortunately can’t read minds

dark pine
primal token
#

JavaScriptObjectNotation

dark pine
#

can you open this link?

#

it works? or its private

sick birch
#

@dark pine please use the paste service

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

sick birch
#

Also the error might be more useful

dark pine
#

thats the right link?

sick birch
#

And the error?

dark pine
#

one min i will post the error

slate swan
#
import disnake
import datetime
from disnake.ext import commands

intents = disnake.Intents.default()
intents.members = True
intents.message_content = True

bot = commands.Bot(
    command_prefix=commands.when_mentioned_or("?"), description = "", intents=intents
)


####################################### anty reklama #######################################

# słowa, których nie można używać na serwerze:
zabronioneslowa = ['https', 'http', 'www', 'discord.gg', 'd.gg']


@bot.event
async def on_message(message):
    if message.author.id == bot.user.id:

        return

    msg_content = message.content.lower()
    curseWord = zabronioneslowa

    if any(word in msg_content for word in curseWord):
        await message.delete()
        embed = disnake.Embed(title="OSTRZEŻENIE!", description="Nie możesz reklamować się na serwerze!", colour = 0xFF0000, timestamp = datetime.datetime.now())
        embed.set_footer(text="© Rynek", icon_url="https://cdn.discordapp.com/attachments/1016070336678207520/1016438417187422218/SAVE_20220713_173556.jpg")
        await message.author.send(embed = embed)


####################################### propozycje #######################################

@bot.command()
async def test(ctx):
    await ctx.send("supa")```
#

why bot.command not working?

#

only client.event

silk fulcrum
#

there is no client.event

#

only bot.event

primal token
#

?

silk fulcrum
#

i mean in their code

primal token
silk fulcrum
#

🚶‍♂️

vale frigate
#

Guys this error local variable 'myview' referenced before assignment and this code await interaction.send("Pick your favourite colour:", view=view and myview, embed=embed, ephemeral=True)

silk fulcrum
#

it will return a bool obj

vale frigate
#

um buttom1.callback = buttom1_callback buttom2.callback = buttom2_callback buttom3.callback = buttom3_callback myview = View(timeout=180) myview.add_item(buttom1) myview.add_item(buttom2) myview.add_item(buttom3) myview2 = View(timeout=190) myview2.add_item(buttom12) myview2.add_item(buttom22) and ```class Dropdown(nextcord.ui.Select):
def init(self):
options = [
nextcord.SelectOption(
label="Red", description="Your favourite colour is red", emoji="🟥"
),
nextcord.SelectOption(
label="Green", description="Your favourite colour is green", emoji="🟩"
),
nextcord.SelectOption(
label="Blue", description="Your favourite colour is blue", emoji="🟦"
),
]

    super().__init__(
        placeholder="Choose your favourite colour...",
        min_values=1,
        max_values=1,
        options=options,```
sick birch
#

Wait did nextcord steal my code

vale frigate
#

Ye

sick birch
#

damn

#

as Okimii always said my examples are garbage 😔

vale frigate
#

lol

slate swan
#

after switching from Windows to Mac, i've been getting an error where, when i interact with a button, i get an error. I have no clue how to fix it..

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 1058, in on_interaction
    await self.process_application_commands(interaction)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/bot.py", line 722, in process_application_commands
    ) and isinstance(interaction.data, interactions.ComponentInteractionData):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/typing.py", line 2385, in __subclasscheck__
    raise TypeError('TypedDict does not support instance and class checks')
TypeError: TypedDict does not support instance and class checks```
vale frigate
#

@silk fulcrum

paper sluice
drifting arrow
#

Is it possible to do a loop, but it doesnt do an initial run?

#

coz whenever I start a loop it always does an initial run

paper sluice
#

what loop is it?

drifting arrow
#

tasks.loop

paper sluice
#

oh, i was thinking about something completely different xD

drifting arrow
#

yeah lol

vale frigate
#

D:

dark pine
#

lol, i cant now even create url to add the bot

#

idk what happened

radiant parrot
#

how do i make my bot execute a command?

sick birch
# dark pine

You probably selected the wrong thing in the URL generator

dark pine
#

i had another choice thats how i added the bot before

#

but its not showing it rn

dull knot
#

I'll make this quick since I'm sleepy as hell. How can I loop through a list? I want to loop through this list of Activities. But I just can't figure out how.

So far, I have this:

Activity = ["Activity 1", "Activity 2", "Activity 3"]

bot = commands.Bot(
    command_prefix=",",
    intents=intents,
    status=disnake.Status.idle,
    activity = disnake.Activity(type=disnake.ActivityType.watching, name=random.choice(Activity))
#

Tried for loops but I couldn't figure it out lol.

#

Still getting used to loops and stuff

#

If I don't reply back, assume I went to sleep lol. I'll figure this out myself inthemeantime

sick birch
dull knot
sick birch
#

You probably want to set up a @tasks.loop

#

And then do what you’re already doing in there

#

There are a few examples in the docs page for it

dull knot
#

This one?

@tasks.loop()
async def status_task() -> None:
await bot.change_presence(status=STATUS-HERE, activity=ACTIVITY-HERE)
await asyncio.sleep(TIME)

Found it on stack overflow lol

dull knot
sick birch
#

Just pass in the loop interval to the decorator

sick birch
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").
dull knot
#

Noted. I'll try this out. Thanks!

dark pine
#

thats the error @ robin

dark pine
dull knot
maiden fable
dull knot
#

lol

#

Haven't really tried it. Since it didn't work kek

radiant parrot
#

any reason this command isnt work? @client.command @commands.has_permissions(kick_members=True) async def warn(ctx, member: discord.Member, *, reason="Not Specified"): if member == ctx.author: await ctx.send("You cannot warn urself!") else: em = discord.Embed(title="**WARNED**", description=f"{member} was warned because: {reason}", color=discord.Color.red()) em2 = discord.Embed(title="**WARNED**", description=f"You have been warned because: {reason}", color=discord.Color.red()) await member.send(embed=em2) await ctx.send(embed=em)

dark pine
#

after 25 hrs of coding kekw

#

lol

radiant parrot
dark pine
#

same thing

radiant parrot
#

just dnt work

dark pine
#

i cant get it it

#

i have read my code for like 15 times

#

i dont even get any errors

#

 python3 main.py
main.py:108: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2022-09-07 19:26:25 INFO discord.client logging in using static token
2022-09-07 19:26:26 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: ce34398c05275ab9630e687e180edf21).
Connected to discord as Spendy#1904

dark pine
# dark pine

it runs and whenever run any command it doesnt work

dark pine
maiden fable
#

I told u

#

await it lol

primal token
radiant parrot
#

how to fix my issue

dark pine
dark pine
maiden fable
#

line number 38, 54 and 59

dark pine
dark pine
dark pine
#

thats the log now

#

im really confused

sick birch
#

@dark pine I'm still not sure what the issue is

dark pine
#

im tired of this, its really difficult even tho i have done other codes with many backtracking n stuff

#

but this one seems really simple to add,remove, and balance commands but its really complicated

dark pine
#

does anything seems wrong on my points commands?

#

the issue is that im still scrolling inbetween the functions

#

i dont see anything wrong, in addition to that i got no errors, not sure whats wrong with it sadly its my first day into discord bots 😦

slate swan
#

how can I send an embed if an error occurred? d.py 2.0 and slash command

tried it like this:

        embed = discord.Embed(colour=728634, title="Error!") 
        embed.add_field(name="Verfügbare Stores", value='')
        await interaction.response.send_message(embed=embed)```
drifting arrow
#

So in my cog I have a function thats suppose to loop but i only want to start it once my interaction completes.
The interaction is a nested class inside of the cog.. i keep getting an error saying "self" was not included...

#

How can I start the loop?

dry kelp
#

@sick birch any other thing for payment?

#

not stripe?

#

i tried using patreon but they're bot its just offline

#

so it won't be able to give roles to users

drifting arrow
#

then there's american/international like venmo?

#

i think it's venmo

dark pine
#

gnomeslayer

#

any thoughts abt my bot?

drifting arrow
dry kelp
#

and im still a minor.

#

patreon bot its not online

dark pine
dark pine
drifting arrow
#

or is it just slow?

dark pine
#

doesnt respond to any command

drifting arrow
dark pine
drifting arrow
#

using @commands.command, the function name acts as the command in discord.
so in this case: .points would be a command.

dark pine
drifting arrow
drifting arrow
# dark pine
@commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        commandname = str(ctx.command)
        commandauthor = ctx.author
        channel = self.client.get_channel(self.config["error_channel"])
        tb = traceback.format_exception(type(error), error, error.__traceback__)
        commandrun = ""
        for i in tb:
            commandrun += f"{i}"
        with open("error_log.txt", "w") as f:
            f.write(commandrun)
        with open("error_log.txt", "rb") as f:
            await channel.send(
                content=f"Command Name: {commandname}, Author: {commandauthor}",
                file=discord.File(f, filename="error_log.txt"),
            )
drifting arrow
#

it'll work for the whole bot. i made a new cog for it

unkempt canyonBOT
slate swan
drifting arrow
#

i think so?

#

if not, just use tb = traceback.format_exception(type(error), error, error.__traceback__) and for i in tb: print(i)

drifting arrow
#

right click a channel in your discord -> copy id

dark pine
drifting arrow
#

yes

#

it takes an int, i usually use a config file to store all this

dark pine
#

ok it runs now, to try and type the commands in?

drifting arrow
#

sure

dark pine
drifting arrow
#

you should get an error

#

i got a config file that looks like this

#

This config hasnt got the error handling

dark pine
#

no errors

drifting arrow
#

gimme a second

dark pine
#

sorry about the questions, its my first day

drifting arrow
dark pine
drifting arrow
dark pine
drifting arrow
dark pine
dark pine
drifting arrow
#

see

#

there we go.

#

paste this into your cogs file.

@commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        commandname = str(ctx.command)
        commandauthor = ctx.author
        channel = self.client.get_channel(123)
        tb = traceback.format_exception(type(error), error, error.__traceback__)
        commandrun = ""
        for i in tb:
            commandrun += f"{i}"
        with open("error_log.txt", "w") as f:
            f.write(commandrun)
        with open("error_log.txt", "rb") as f:
            await channel.send(
                content=f"Command Name: {commandname}, Author: {commandauthor}",
                file=discord.File(f, filename="error_log.txt"),
            )

and remove any other on_command_error code

#

and make sure you import traceback import traceback

slate swan
dark pine
drifting arrow
drifting arrow
#

if the error happens in a general chat with lots of chatter, do you really want the error to fly off into oblivion?

#

and it's useless being sent to a random user. why would they report it?

#

so send it to a discord channel

dark pine
#

so now to use the command?

drifting arrow
#

yes

slate swan
drifting arrow
#

We arent using webhooks?

dark pine
drifting arrow
#

but this time your error appeared in the target channel 🙂

#

Read the traceback and find out what you're doing wrong.

dark pine
dark pine
drifting arrow
#

do you have a function called points or hel? or did you assign an alias to any function(command) called points or hel

drifting arrow
#

reading ur code now,

dark pine
#

oh sorry

drifting arrow
#

im confused as to what the category thing is anyway

dark pine
#

the cogs might be more organized here

dark pine
#

all i wanted to code is a bot with add, remove and balance commands

#

for imaginary points

slate swan
drifting arrow
slate swan
#

Hey!

I have a def that if it is true it does something, and the information is in a .json file, How would i def it in my main file?

  def botlogging(ctx):
    return str('whatever i need here' in settings ["botlogging"]
dark pine
#

how?

#

i've import em

slate swan
#

hello guys please help me with this erreur

slate swan
#

and go to discord developer portal and enable all bot intents

#

tysm bro

#

np

#

❤️

#

❤️

drifting arrow
#

I know one of them spits out error

slate swan
#

dump

#

what would i put under myvariable

drifting arrow
#

im still confused as to what you want.

slate swan
#

i want to def botlogging

drifting arrow
#

when working with a json file you first have to load it into a variable. then you do your editing to it, then you save it

slate swan
#

but in a .json file i have if it is true or false

drifting arrow
#
{
  "botlogging": true
}```
#

a json file is just a dictionary

slate swan
#

thats what i have

#

but i want to def botlogging in my main file

#

how would i get that info

#

like i have

#
def Staff(ctx):
    return str(ctx.author.id) in settings["staffId"]
drifting arrow
#
myfile = ''
with open('myjsonfile.json', 'r') as f:
    myfile = json.load(f)
if myfile['botlogging']:
  myfile['botlogging'] = False,
  with open('myjsonfile.json', 'w') as f:
      f.write(json.dumps(myfile, indent=4))
#

then send it to the main self so create a variable in the init, called self.myfile or whatever. idc. and load the json file there

#

then to reference it later, do self.myfile etc

#

and if you want to update it, self.myfile = ...

slate swan
#

thanks

drifting arrow
#

alright.

#

now that I've gotten those nerds out the way. can someone help me with my issue? 😄

slate swan
#

whats ya issue?

#

ill see if i can help

drifting arrow
#

probably a bit more complex than what you can handle but sure I'll shoot it.
I have a child class and I am trying to target the parent class and start a loops event xD

#

had to reply to someone.

slate swan
#

yep to complex, sorry

drifting arrow
#

It's all g

slate swan
#

guys my bot i showing link of picture in message why ? i want only picure without link

#

i dont need link in message

#

who can help me please

#

how would i check

#

say like a string is 5e712ecf-2fbb-4f37-a462-155917378803 , how would i check how many "-" are in said string

drifting arrow
drifting arrow
slate swan
#

im new in python I do not understand

slate swan
slate swan
slate swan
#

how do i make my bot delete my command ?

naive briar
slate swan
# naive briar ?

when i send command like !image he send command and he delete my message of command

#

im not good at english

torn sail
#

await ctx.message.delete()

naive briar
slate swan
#

alright thx

rare echo
#

i like that you refer to the bot as “he”

sick birch
#

English may not be their first language. Plenty of languages, like French, assign genders to most of their words

rare echo
#

it was just funny to see in context

muted mountain
#

How do I change this info

naive briar
muted mountain
#

Literally not in any settings

naive briar
#

!d discord.Guild.edit

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

Edits the guild.

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

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

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

Changed in version 2.0: The newly updated guild is returned...
muted mountain
naive briar
cobalt relic
#

I am trying to get the status of a user to see if that user is online (my other bot), however that status it returns is a class type. How can I convert the class to a string to show the value in my if statement. Any ideas?

@tasks.loop(seconds=5.0)
async def printer():
    ## DEFINES USERS // CHANNELS
    guild = StatusBot.get_guild(1014394890748178432)
    channel = StatusBot.get_channel(1017200174914879609)
    DaveModPremium = guild.get_member(1013496497603625011)
    DaveMod = guild.get_member(998302501356974220)

    print(type(DaveMod.status))
    print(type(DaveModPremium.status))
    print(channel)

    ##SENDS ALERT IF BOT IS DETECTED OFFLINE

    if DaveModPremium.status or DaveMod.status != 'online':
        print(DaveModPremium.status)
        await channel.send(f'{DaveModPremium.mention} is Offline!')
        print('DaveModPremium Is OFFLINE!')```
naive briar
# cobalt relic I am trying to get the status of a user to see if that user is online (my other ...

You can use str() for that

@tasks.loop(seconds=5.0)
async def printer():
    ## DEFINES USERS // CHANNELS
    guild = StatusBot.get_guild(1014394890748178432)
    channel = StatusBot.get_channel(1017200174914879609)
    DaveModPremium = guild.get_member(1013496497603625011)
    DaveMod = guild.get_member(998302501356974220)

    print(type(DaveMod.status))
    print(type(DaveModPremium.status))
    print(channel)

    ##SENDS ALERT IF BOT IS DETECTED OFFLINE

    if str(DaveModPremium.status) or str(DaveMod.status) != 'online':
        print(DaveModPremium.status)
        await channel.send(f'{DaveModPremium.mention} is Offline!')
        print('DaveModPremium Is OFFLINE!')```
Or you can also use `isinstance()`
#

It's up to you

cobalt relic
#

ive tried str() but it does not seem to return the expected results. I will try out the isinstance() method as you mentioned though

#

and str() returns <class 'discord.enums._EnumValue_Status'>

naive briar
#

Hmmmm

slate swan
#

help please

cobalt relic
#

i think that is my own issue, one moment

naive briar
#

Maybe you could try something like

DaveMod.status != discord.Status.online

If isinstance don't work

naive briar
cobalt relic
#

ive give it a go, thanks

unkempt canyonBOT
#

Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me

Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!

naive briar
slate swan
#
import discord
from discord.ext import commands, tasks
from datetime import datetime

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

@tasks.loop(seconds=60)
async def task():
    now = datetime.now()
    current_time = now.strftime("%H:%M %p")
    await bot.change_presence(status = discord.Status.online, activity = discord.Game(f' With Misk1'))

@task.before_loop
async def before_loop():
    await bot.wait_until_ready()
    print('Ready')

task.start()

@bot.command()
async def Server(ctx):
    await ctx.message.delete()
    await ctx.send("** Server is online have fun ! @everyone  **")

@bot.command()
async def image(ctx):
   await ctx.message.delete()
   await ctx.send("https://media.discordapp.net/attachments/1002356883899826258/1017156567818313791/Untitled-122.png")

@bot.command()
async def ip(ctx):
    await ctx.message.delete()
    await ctx.send("Fivem ==> Console (F8) ==>  Copy/Past ==>  Connect 92.42.45.132:30120 ")

bot.run("")  ```
cobalt relic
slate swan
#

so ?

naive briar
#

Well, it looks like the error is saying that

await ctx.send(...)

line isn't in the same indent as the

await ctx.message.delete()
cobalt relic
naive briar
cobalt relic
#
if DaveMod.status or DaveModPremium.status != discord.Status.online:
    print(DaveModPremium.status)
    #await channel.send(f'{DaveModPremium.mention} is Offline!')
    print('DaveModPremium Is OFFLINE!')```
cobalt relic
#

indent is wrong because of discord

naive briar
#

Why do you have to check if DaveMod.status exist?

#

!or

unkempt canyonBOT
#

When checking if something is equal to one thing or another, you might think that this is possible:

# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
    print("That's a weird favorite fruit to have.")

While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.

So, if you want to check if something is equal to one thing or another, there are two common ways:

# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
    print("That's a weird favorite fruit to have.")

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
cobalt relic
#

im not, im checking the status (it is my other discord bot, i am making a separate bot to detect when the bot goes offline.)

cobalt relic
#

i seee

#

I had a good feeling thats where it went wrong

#

thank you for that, ill give it another go

heady citrus
#

say if i forked discord.py & used that fork instead of the official one.. What are the cons if there are any

fickle hamlet
#

You will have to maintain your fork if you want to keep using it instead of discord.py

primal token
#

By customizing your installation or forking the library, uppon updating its state would probably be erased so your edits would be erased, over overwriting methods in your code and only have future compatibility issues

#

But since dpy almost never edits its old codebase the compatibility issues would be rare, but as i++ has said, your custom installation wouldnt be up to date or compatible for future projects with other original installations depending on the implementation of future endpoints so you would need to continue to maintain it

tawdry laurel
#

does anyone know how to get context menu in a cog discord 2.0?

sick birch
jagged adder
#

how do i delete a msg when someone reacts to a msg sent by my bot? ive worked out how to add the emoji, now i want to delete the msg if someone reacts with that emoji

#

i think its related to on_raw_reaction_add() but im not having much luck through google

paper sluice
#

use Bot.wait_for and wait for that event, and then you can delete the message

jagged adder
#

so id set it up as a bot.event?

#

else where would i be putting the wait_for

paper sluice
#

oh wait, which message do you want to delete when someone reacts?

jagged adder
#

so if i ctx.send("apple") and add an apple emoji to it, i want the "apple" msg to be deleted

#

if someone reacts to that msg with an apple emoji

paper sluice
#

and you can check for emojis as well

jagged adder
#

so... id need to write it as a new command?

#

or put it under the one that made the msg

paper sluice
#

just under that

jagged adder
#

ah

jagged adder
#

so itd be like

async def fruit(ctx):
  apple = "apple"
  ctx.send(apple)
  # add emoji stuff

  bot.wait_for(on_reaction_add, check=check)
  if ... == True
  ctx.message.delete()

?

paper sluice
#

you want to delete the apple message right

jagged adder
#

yes

paper sluice
#

so store it in a variable and delete that, ctx.message is the message which was used to call the command like !fruit

jagged adder
#

ah

paper sluice
#

and .delete() is a coro, so await it

jagged adder
#

the ctx.message part i get

paper sluice
#

just like this

msg = await ctx.send(...)
...
await msg.delete()
jagged adder
#

ah

slate swan
#
async def fruit(ctx):
  apple = "apple"
  message = await ctx.send(apple)
  # add emoji stuff

  bot.wait_for(on_reaction_add, check=check)
  if ... == True
  await message.delete()```
jagged adder
#

yeah i got this rn

msg = await ctx.send(f"...")
    await msg.add_reaction('⚔️')
#

so i alrdy got a variable that refers to it right

slate swan
#

yep

#

just make sure the bot has permissions to add reactions or you might run in errors

jagged adder
#

so i just need the latter part

#

yeah i know the adding works as i alrdy tested that

jagged adder
slate swan
#

yeah

jagged adder
#

why ?

naive briar
#

!d discord.ext.commands.Bot.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/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
jagged adder
#

if this wait_for never times out, does that mean that if i spawn a ton of these msgs that ill clog up my system?

#

if i dont set a timeout

slate swan
jagged adder
#

and also, i presume that when i restart the bot to update something, the emoji-delete wont work either right

naive briar
#

Yeah

jagged adder
#

thought so

#

maybe i could set it to auto-delete after it times out

slate swan
#

Can someone guide me to some resource where i can get help with the API rate limit i am running into frequent bans so was looking for ways to get the bot operations in limits