#discord-bots

1 messages ยท Page 977 of 1

maiden fable
#

U get ARM processors

lofty tinsel
slate swan
#

that's enough to run a full instance of VSCode on the server

maiden fable
#

Haha ofc

slate swan
#

that's gonna be useful

sick birch
#

Very

maiden fable
#

I used to use VSC on 4 GB RAM with Windows 10

sick birch
#

Do they provide other services though?

#

I might have to consider switching

slate swan
sick birch
#

Specifically domains, load balancers

slate swan
#

imagine vsc + discord

#

im on 16 on my main rig

sick birch
#

aha they do have a load balancer

slate swan
#

nvmd

#

why oracle giving these free services??

lofty tinsel
#

someone can help me?

maiden fable
#

They want to get yr cc info ๐Ÿ‘€

slate swan
#

oh no

#

scam 2022

sick birch
#

There's probably a bunch of fine-text things you might want to read

#

Before you get charged for something you didn't know

maiden fable
#

Well, two of my friends are using the same to host their bots

#

One of them has been using since a few months now and Raven using it since like 2 months or smth

slate swan
#

i mean oracle is pretty trusted, and the only other options i know of are AWS and linode, and they offer nowhere near the value of oracle

maiden fable
#

Yea haha

#

That is why I also tell about Oracle. It is trusted as much as AWS is

brittle flume
#

Please help

Ignoring exception in on_message
Traceback (most recent call last):
  File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/client.py", line 375, in _run_event
    await coro(*args, **kwargs)
  File "/data/data/com.termux/files/home/codes/otaku/extensions/afk.py", line 47, in afk_listener
    await in_afk_check(message)
  File "/data/data/com.termux/files/home/codes/otaku/extensions/afk.py", line 34, in in_afk_check
    data = json.load(f)
  File "/data/data/com.termux/files/usr/lib/python3.10/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/data/data/com.termux/files/usr/lib/python3.10/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/data/data/com.termux/files/usr/lib/python3.10/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 3 (char 2)
maiden fable
#

Show yr JSON

slate swan
#

it was given extra data

maiden fable
#

Nvm its discord

brittle flume
maiden fable
#

Wait what

#

Prolly an invisible char

brittle flume
maiden fable
#

Weird

brittle flume
#

code:

from discord import app_commands
from datetime import datetime
from typing import Optional
import discord
import config
import json


@app_commands.command()
async def afk(interaction, note: Optional[str]):
    if note is None:
        note = 'No note provided'
    with open("databases/afk.json", "r") as f:
        data = json.load(f)
    user = interaction.user
    data[user.id] = note
    if 'AFK' != (user.display_name).split()[0]:
        nick = "[AFK] " + user.display_name
        try:
            await user.edit(nick=nick)
        except:
            pass
    
    await interaction.response.send_message(
        f"Added to AFK list ; Note : {note}", ephemeral=True
    )

    with open("databases/afk.json", "w") as f:
        json.dump(data, f, indent=4)


async def in_afk_check(message):
    with open('databases/afk.json', 'r') as f:
        data = json.load(f)
    if message.author.id in data.keys():
        await message.author.reply('Welcome Back!')
        del data[message.author.id]
        name = (message.author.display_name).split()
        if "[AFK]" == name[0]:
            await message.author.edit(nick=''.join(name[1:]))
        with open("databases/afk.json", "w") as f:
            json.dump(data, f, indent=4)

async def afk_listener(message):
    if message.author.bot:
        return
    await in_afk_check(message)
    
    

async def setup(bot):
    bot.tree.add_command(afk, guild=config.guild)
    bot.add_listener(afk_listener, 'on_message')

maiden fable
#

Weird

brittle flume
#

๐Ÿ˜•

slate swan
#

just don't use json๐Ÿฅบ

hushed galleon
#

seems you're writing to it correctly, double check that you're looking at the right file

#

also message.author.reply() should be message.reply()

unkempt canyonBOT
#

When using JSON, you might run into the following error:

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

This error could have appeared because you just created the JSON file and there is nothing in it at the moment.

Whilst having empty data is no problem, the file itself may never be completely empty.

You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.

Different data types are also supported. If you wish to read more on these, please refer to this article.

spring flax
#

nevermind that, it seems a different error

brittle flume
lofty tinsel
#

why my cogs doesnt works?

meager quartz
#

I need help for urm... anti spam detection

slate swan
# brittle flume .

why are you even using json? use an actual database like sqlite or postgresql and just use there async bridges so it would be aiosqlite and asyncpg

lofty tinsel
brittle flume
#

It's just one small server

slate swan
#

and just use the kwarg

#

!d discord.ext.commands.Bot.help_command

unkempt canyonBOT
slate swan
#

.

#

just set it to none

slate swan
slate swan
#

Fellow logo_sublimetext user

lofty tinsel
carmine pasture
#

anyone here can help me i got stuck making my bot

slate swan
brittle flume
slate swan
#

Rly hes playing minecraft

lofty tinsel
#
import discord
from discord.ext import commands

class CogOwner(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
                self.bot.remove_command('help')

@commands.command()
async def help(self, ctx):
    embed = discord.Embed(title='**๐Ÿ“‚ | __Commands List__**\n\u2800', color=0x2F54C7)
    await ctx.send(embed=embed)
slate swan
#

Bruh

lofty tinsel
#

under self.bot = bot ?

slate swan
#

Ye

slate swan
unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

carmine pasture
# slate swan Yes

ok so i am making a discord bot with python and i am trying to get it to post a help page in embed but the code just wont work and its not showing any error. i can paste the code here

slate swan
#

show code

brittle flume
brittle flume
#

Lol

slate swan
lofty tinsel
carmine pasture
slate swan
sick birch
slate swan
carmine pasture
#

alr

slate swan
# brittle flume I give up

its quite easy to use a database you just install aiosqlite which is a library you can read there docs and down the sqlite browser which can make things much easier for you

lofty tinsel
sick birch
#

Use an ORM ๐Ÿ—ฟ

lofty tinsel
#

like that?

slate swan
#

Nice

#

i mean yeah it can be their

#

I wonder how he write the help embed title

lofty tinsel
#

command does not work

slate swan
#

because it got removed bro

#

and download pyright

#

Lmao

lofty tinsel
slate swan
#

a type checker

#

Listen

#

In ur bot var

#

it screams errors at you

#

Put help_command=None

#

And remove this

carmine pasture
#

what if i dont want to make a help command just put an embed up that tells you all the commands u could use

#

cause my embed aint working

#

this is my code

#
async def Embed(message):
    if message.content.startswith('c.commandlist'):
      embedVar = discord.Embed(title='Help', description = 'commands', color=1)
      embedVar.add_field(name='c.intro', value='introduces you to the settler', inline=False)
      embedVar.add_field(name='c.start', value='Builds your first settlement', inline=False)
      embedVar.add_field(name='c.gather', value='gathers resources', inline=False)
      await message.channel.send(embed=embedVar)```
slate swan
#

just subclass the help command

dull terrace
#

hey guys so i have this issue on iphones

slate swan
#

?

dull terrace
#

when i replace the image file with a new one

#

itll make the image "shake"

slate swan
#

Its discord bots not i phone support

dull terrace
#

sparky you dork

#

i was gonna ask if anyone has run into the problem and if they found ways around it

#

i.e. moving the file to an embed box

slate swan
#

..

dull terrace
#

is very much a bot problem

slate swan
#

I cant understand

dull terrace
#

hold on ill edit the video so i can send it

slate swan
#

Ok.

carmine pasture
#

Can someone here please mabye type a functioning embed code that works and paste it here?

#

I need to see what i did wrong in mine

slate swan
#

Show ur code?

carmine pasture
#

i did

#

alr lemme paste it again

slate swan
#

Uh wair i get it

carmine pasture
#
async def Embed(message):
    if message.content.startswith('c.commandlist'):
      embedVar = discord.Embed(title='Help', description = 'commands', color=1)
      embedVar.add_field(name='c.intro', value='introduces you to the settler', inline=False)
      embedVar.add_field(name='c.start', value='Builds your first settlement', inline=False)
      embedVar.add_field(name='c.gather', value='gathers resources', inline=False)
      await message.channel.send(embed=embedVar) ```
slate swan
#

Ok so whats the error

carmine pasture
#

there is no error message

slate swan
#

Huh?

carmine pasture
#

just the bot doesnt respondt

slate swan
#

Does the event trigger

carmine pasture
#

well i type the message but no response

slate swan
#

Not sure what is that

dull terrace
#

massive screen shake only on iphone

slate swan
slate swan
# carmine pasture Can someone here please mabye type a functioning embed code that works and paste...
embed = discord.Embed(title="uwu", description="the most uwu embed in the world", colour=discord.Color.blue())
embed.set_thumbnail(url="SOME URL")
embed.set_image(url="SOME URL")
embed.set_footer(text="uwuest footer", icon_url="SOME URL HERE")
embed.set_author(name="uwu name", icon_url="SOME URL", url="SOME URL")
embed.add_field(name="uwu field name", value="uwu value", inline=False)
embed.insert_field_at(0, name="field at uwu name",  value="field at uwu value", inline=False)
dull terrace
#

thanks, has anyone ran into this though ablobsweats

dull terrace
#

on every other device it just shows a loading symbol for a fraction of a second

#

on iphone it likes to shake the previous image in your face

slate swan
fallow mauve
#

hey so ive asked about this multiple times, how do i make a command where when used with a word or phrase after it it will add the word or phrase to a list in a json file

slate swan
#

Where do u guys get pfp from

carmine pasture
dull terrace
#

alright i better go to help channels froggy_chill

slate swan
#

I also need 1 shipit

slate swan
unkempt canyonBOT
slate swan
fallow mauve
# slate swan gib example

ok so if i said !list add [word or phrase] it would add the word or phrase to a list in a json file, and if i said !list remove [word or phrase] it would see if that word or phrase is in the list and remove it

slate swan
slate swan
#

use a proper db

fallow mauve
dull terrace
slate swan
dull terrace
#

it's beyond distracting

slate swan
#

or mongoDB (json-like)

#

๐Ÿ‘‹

slate swan
dull terrace
#

i'm kinda shocked no one else has had the same issue here

slate swan
#

maybe discord hates you๐Ÿ˜”

dull terrace
#

i wonder if it happens on all iphones or specific models

slate swan
#

its probably just a bug in your specific client

#

it doesnt matter your phones model

dull terrace
#

this is a beta testers client

slate swan
#

welll thats why

#

beta clients have many bugs

dull terrace
#

no as in a beta tester for the game

#

they have a regular discord client as far as im aware

slate swan
#

oh i thought you ment beta clients

#

cuz discord lets you try their beta clients

dull terrace
#

has anyone else found this thing with iphones though

#

i can just ignore it if it's an edge case

slate swan
#

has it happen everytime?

maiden fable
#

What happened

dull terrace
#

yeah it happens whenever the image changes

slate swan
#

oof

dull terrace
maiden fable
#

What happens

#

The one second blackout?

dull terrace
#

it makes the image do that shaking thing

slate swan
maiden fable
#

O

slate swan
#

are you?

#

i got 6๐Ÿ˜… ๐Ÿ’€

dull terrace
#

definitely 7 if you follow order of operations in python

maiden fable
#

It should be -1

dull terrace
#

multiplication first

maiden fable
#

BODMAS

dull terrace
#

wait

maiden fable
#

Yea

dull terrace
#

yeah -1 is the answer

slate swan
#

๐Ÿ˜”

dull terrace
#

!e print(2-2*3+3)

unkempt canyonBOT
#

@dull terrace :white_check_mark: Your eval job has completed with return code 0.

-1
slate swan
#

Python doesnt lie!

#

no reason๐Ÿ˜ณ

dull terrace
#

the computer failed

#

can't do maffs

#

it's not a "jenious"

maiden fable
#

Can we take this to an ot channel now?

slate swan
#

hunter bad at math๐Ÿ˜”

maiden fable
#

Stop it

slate swan
sick birch
#

Let's keep it OT please

frozen patio
#

Hello! I have an error where I restart my bot I cannot pull the warnings from a user. Why is that?

sick birch
#

(I mean on-topic, not off-topic)

sick birch
sick birch
#

Ah that makes sense

#

Looks like lines is an empty list

frozen patio
#

Cause I have 3 lines in the warn file

sick birch
#

Where are you defining lines?

frozen patio
sick birch
#

Should look like

lines = ...
frozen patio
#

Right here

sick birch
#

Looks like the file might be empty

frozen patio
sick birch
#

Hmm

#

Try printing lines to debug

frozen patio
#

The file has 3 lines it

sick birch
#

Also should probably be using a database for this

frozen patio
#

I do not think this will be used much so no need to set up a database

sick birch
#

Would still solve most issues relating to reading/writing

#

Sine doing that manually is always tricky

frozen patio
#

Could it be this that is causing it?

sick birch
#

Something's going while trying to readlines() and it's not giving an error to clue us into as what might be going wrong

#

I doubt it

frozen patio
#

I have a ticket file too

#

That is opening

#

When that opens

sick birch
#

Compare this code to that and see what's off

#

Given the ticketing system works

frozen patio
#

It does

#

100%

#
@client.event
async def on_ready():
    async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
        pass

    async with aiofiles.open("ticket_configs.txt", mode="r") as file:
        lines = await file.readlines()
        for line in lines:
            data = line.split(" ")
            client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]

    print(f"{client.user} is online and ready!")
    await client.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"for s!help"))
    client.uptime_start = time.time()

    client.reaction_roles = []

    for guild in client.guilds:
        client.warnings[guild.id] = {}
        
    async with aiofiles.open(f"{guild.id}.txt", mode="a") as temp:
        pass

    async with aiofiles.open(f"{guild.id}.txt", mode="r") as file:
        lines = await file.readlines()

        for line in lines:
            data = line.split(" ")
            member_id = int(data[0])
            admin_id = int(data[1])
            reason = " ".join(data[2:]).strip("\n")

        try:
            client.warnings[guild.id][member.id][1].append((admin_id, reason))
            client.warnings[guild.id][member.id][0] += 1

        except KeyError:
            client.warnings[guild.id][member.id] = [1, [(admin_id, reason)]] ```
#

@sick birch This is what is in my on_ready event

maiden fable
#

Bro

frozen patio
#

Yeah?

maiden fable
#

I, uhhh

vocal snow
#

text file...

frozen patio
#

Oh

#

Yeah ik

maiden fable
#

Not that, but yea that too

frozen patio
#

Must be

maiden fable
#

Too much code in on_ready

sick birch
#

There's so much that can go wrong there, oh my

frozen patio
#

Well the console says:

slate swan
#

๐Ÿ˜”

frozen patio
#

๐Ÿค”

slate swan
frozen patio
#

How?

#

It was defined before I used it

slate swan
#

member_id is a variable that was assigned after that reference

frozen patio
slate swan
#

!e

def a():
    print(a)
    a = 1

a()
frozen patio
#

Yea

unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 5, in <module>
003 |   File "<string>", line 2, in a
004 | UnboundLocalError: local variable 'a' referenced before assignment
vocal snow
# frozen patio

if lines is empty the code in the for loop won't be executed

frozen patio
#

So that needs to go under the try lines ๐Ÿ˜

vocal snow
#

and have you considered using a light database or even pickle

sick birch
#

It's going to be almost impossible to find the root cause of the issue with that much error-prone code

#

It could really be coming from anywhere

#

Or be coming from 20 levels deep

frozen patio
#

Yea I cannot seem to find it's cause Hmm

#

So could it be coming from my warn command?

#
client.command()
@commands.has_permissions(manage_messages=True)
async def warnings(ctx, member: nextcord.Member=None):
    if ctx.author.id in blacklist: 
        bl = nextcord.Embed(title="You are blacklisted!", description="You have been blacklisted from Slytherin!", color=0xff0000)
        bl.set_footer(text=footer)
        bl.timestamp = datetime.now()
        await ctx.send(embed=bl)
    else:
        if member is None:
            return await ctx.send("The provided member could not be found or you forgot to provide one.")
    
        embed = nextcord.Embed(title=f"Displaying warnings for {member.name}", description="", colour=0x003fff)
        try:
            i = 1
            for admin_id, reason in client.warnings[ctx.guild.id][member.id][1]:
                admin = ctx.guild.get_member(admin_id)
                embed.description += f"**Warning {i}** given by: {admin.mention} for: *'{reason}'*.\n"
                i += 1

            await ctx.send(embed=embed)

        except KeyError: 
            await ctx.send("This user has no warnings.")
#

This is the command that will not let me pull their warnings.

frozen patio
#

It has to be in this coming from this command

slate swan
#

so i want to make my bot status was watching then {amount of lines in a text file} any ideas how I would?

sick birch
frozen patio
#

Maybe I forgot to open the files in the command Hmm

#

But if

sick birch
#
def get_lines():
  # return num of lines in a text file

bot = commands.Bot(activity=discord.Activity(...))
frozen patio
#

I opened them in the on_ready event

sick birch
#

You shouldn't be doing that in on_ready

frozen patio
#

Why would I need to open them again

sick birch
#

It can be the cause of all sorts of weird issues

frozen patio
#

Yea

#

I should move all of that to the warnings command shouldn't I?

sick birch
#

Probably

#

But honestly this is going to be pretty difficult to diagnose and fix

slate swan
#

ye

slate swan
#

or summit like dat

#

then for bot status

sick birch
#

Yeah that works. Since this is pre-bot-start it's fine to block

slate swan
#

{fnum_lines}

sick birch
#

You don't want to do that after your bot starts, however

slate swan
#

ye

#

ok ye works

#

ty

sick birch
#

Anytime

paper sluice
#
ctx.author.activities

is empty :/

#

its an empty tuple like ()

maiden fable
#

@slate swan what r yr intents

paper sluice
maiden fable
#

So?

#

And in yr code?

#

intents=discord.Intents.all() in yr bot constructor

frozen patio
maiden fable
#

No

#

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

frozen patio
#

Wait no I did not

#

I got this error :/

paper sluice
#
@bot.command()
async def status(ctx, user: discord.Member):
  await ctx.send(user.activities[0].name)```
frozen patio
#

But where

#

And How do I fix this

midnight crane
#

whats the best db for python bots?

slate swan
midnight crane
#

somthing simple bc i yet to learn how to use db

slate swan
midnight crane
slate swan
#

and to see data in a ui just use the sqlite browser

slate swan
slate swan
dull terrace
#

annoying bug i can't work out

slate swan
dull terrace
#
@client.event
async def on_button_click(interaction):
    data = await interaction_common(interaction)
    if not data:
        return```
so a cooldown is in `interaction_common` if it triggers then the function returns `False` which stops `on_button_click` proceeding
but it seems to retry it when the cooldown is over?
`disnake.errors.InteractionResponded: This interaction has already been responded to before`
It seems to not fail to interact when i hit a button while on cooldown, but it doesn't proceed and do anything
#

it should be giving the little error this interaction failed or whatever

#

it seems to be literally saving every button push while on cooldown and retrying as soon as the cooldown is over and gives me the same error for each one

midnight crane
dull terrace
#

i guess i could do a check at the start of every single interaction to see if it has already responded but that seems wasteful

velvet haven
#

my commands are not working idk why

frozen patio
#

Why does it do this

#

Every time I restart the bot

proud rain
#
    color=self.log_channel.guild.get_member(after.id).colour,
AttributeError: 'NoneType' object has no attribute 'colour'

I keep getting this error

Code:

    
@Cog.listener()
    async def on_user_update(self, before, after):
        if before.name != after.name:
            embed = Embed(title="Navne Skifte",
                          colour=after.colour,
                          timestamp=datetime.utcnow())

            fields = [("Fรธr:", before.name, False),
                      ("Efter:", after.name, False)]

            for name, value, inline in fields:
                embed.add_field(name=name, value=value, inline=inline)

            await self.log_channel.send(embed=embed)

        if before.discriminator != after.discriminator:
            embed = Embed(title="Discriminator Skifte",
                          colour=after.colour,
                          timestamp=datetime.utcnow())

            fields = [("Fรธr:", before.discriminator, False),
                      ("Efter:", after.discriminator, False)]

            for name, value, inline in fields:
                embed.add_field(name=name, value=value, inline=inline)


            await self.log_channel.send(embed=embed)```
worldly solstice
#

I heard that if i ask async questions in here i will get roasted, is that true? ๐Ÿ‘€

dull terrace
#

this is driving me crazy

#

it's literally resending the button info up to 30 seconds later after a cooldown disnake.errors.InteractionResponded: This interaction has already been responded to before

#

it definitely hasn't responded already

#

and it shouldn't be doing anything after being returned

slate swan
frozen patio
#

Why is my bot doing this after I restart it?

slate swan
frozen patio
slate swan
frozen patio
#

It should open on_ready

#

I have it set up like that ๐Ÿ˜

slate swan
#

you dont use a .txt file as a database

worldly solstice
# slate swan no you wont. if its not fitting to discord bots go to <#630504881542791169>

It is actually!

project = "ExoWorlds"

class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):

        if message.author == self.user:
            return


async def get_exo_floor():
    s = AsyncHTMLSession()
    r = await s.get('https://exoworlds.io/marketplace')
    await r.html.render(wait=3, retries=5, reload=True, sleep=2)
    soup = await BeautifulSoup(r.html.html, "html5lib")
    c = await soup.find('div',attrs={'class':'marketplaceStats__item'})
    print(c.text)
    exo_floor = c.text
    return exo_floor


async def background_task():
    await client.wait_until_ready()
    while not client.is_closed():

        await asyncio.sleep(5)

        exo_floor = await get_exo_floor()
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        #change name of discord channel
        voice_channel_2 = client.get_channel(964211130627162192)
        await voice_channel_2.edit(name="Exo MP Floor: " + str(exo_floor))
        print(current_time + str(" Exo Floor updated to ") + str(exo_floor))



client = MyClient()
client.loop.create_task(background_task())
client.run(token)

When i run this i always get

Task exception was never retrieved
future: <Task finished name='Task-1' coro=<background_task() done, defined at C:\Users\Alex\Desktop\exo_role\role_bot-main\src\asynctest.py:38> exception=RuntimeError('This event loop is already running')>
Traceback (most recent call last):
  File "C:\Users\Alex\Desktop\exo_role\role_bot-main\src\asynctest.py", line 44, in background_task
    exo_floor = await get_exo_floor()
  File "C:\Users\Alex\Desktop\exo_role\role_bot-main\src\asynctest.py", line 30, in get_exo_floor
    await r.html.render(wait=3, retries=5, reload=True, sleep=2)
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\site-packages\requests_html.py", line 598, in render
    content, result, page = self.session.loop.run_until_complete(self._async_render(url=self.url, script=script, sleep=sleep, wait=wait, content=self.html, reload=reload, scrolldown=scrolldown, timeout=timeout, keep_page=keep_page))
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 622, in run_until_complete
    self._check_running()
  File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 582, in _check_running
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

and i have no idea how to fix that. I tried to import nest_asyncio and apply it but this would just never return anything at all

slate swan
#

as the file extension shows its for text and not saving data

frozen patio
slate swan
worldly solstice
#

but the only thing thats relevant right now for this issue

slate swan
#

Well the error quite says it.

frozen patio
#

Yeah

worldly solstice
frozen patio
slate swan
frozen patio
#

Maybe if I open the file in the warning command :0

sick birch
#

Itโ€™s also much less error prone and easier to troubleshoot

slate swan
frozen patio
#

But there has to way to pull a .txt file

#

to get the data after you restart the bot

sick birch
#

Probably in setup hook

slate swan
#

@sick birch btw any new news on the new thread for the channel?

slate swan
sick birch
#

Not yet. Give us a bit

slate swan
stuck oyster
#
disnake.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
#

what does this mean

pliant gulch
#

Your responding to an expired interaction

stuck oyster
#
@client.event
async def on_ready():
  client.add_view(MyView2())
  client.add_view(MyView1())
  client.add_view(MyView())```
Won't this stop it?
pliant gulch
#

I don't see how this would be causing the issue

#

Just make sure if you are gonna be defering and sending followup messages, that you send it within 15 minutes

#

After 15 the interaction token will expire and invalidate

stuck oyster
pliant gulch
#

Why are you defering then right after sending a message?

#

Couldn't you just respond already without the followup

stuck oyster
pliant gulch
#

What?

stuck oyster
#

I interacted with the button and the error told me to defer it so thats what I did

pliant gulch
#

That;s odd, never expirenced that before

hushed galleon
unkempt canyonBOT
#

disnake/errors.py lines 304 to 312

msg = (
    "Interaction took more than 3 seconds to be responded to. "
    'Please defer it using "interaction.response.defer" on the start of your command. '
    "Later you may send a response by editing the deferred message "
    'using "interaction.edit_original_message"'
    "\n"
    "Note: This might also be caused by a misconfiguration in the components "
    "make sure you do not respond twice in case this is a component."
)```
stuck oyster
#

yes

hushed galleon
#

does your unknown interaction error come up often? if its only occasional then its likely caused by internet latency

stuck oyster
#

comes up often

hushed galleon
#

you're creating the ticket channel before the defer right? maybe thats the bottleneck

hushed galleon
#

you can time it to make sure - personally i got 0.9s of delay when executing create_text_channel - and if its the issue, you should place the defer at the start, do whatever you need in between, and send your followup at the end

#

i think your indentation is a bit messed up

#

the else clause along with the line under it is underindented, while the two lines after that are overindented

#

btw collections.Counter would be a good tool for this

#

!d collections.Counter

unkempt canyonBOT
#

class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.

Elements are counted from an *iterable* or initialized from another *mapping* (or counter):

```py
>>> c = Counter()                           # a new, empty counter
>>> c = Counter('gallahad')                 # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args
hushed galleon
#

also you dont need to fetch every user, the Member object itself can be used as the dict key

#

you also have the members intent enabled, right oops you dont need it here

slow estuary
#

when I run my code I get this error, and I have no idea how to fix it

#

It was working a while ago, but I needed to update my client secret so I think that is causing the problem, but I have no idea how to fix it

hushed galleon
#

you need to regenerate your token and copy it from the application page

slow estuary
#

I have multiple times

#

maybe it is a problem with docker?

hushed galleon
#

maybe, if your config somehow didnt get updated to include the new token

slow estuary
#

do you want me to send the full error message?

#

wait i think i know why

#

nevermind

#

I have no idea

hushed galleon
#

try printing your token when you pass it into the bot to make sure its the correct one you're expecting

slow estuary
#

the error is coming from bot. run

#

which does reffer to the defined token

#

bot = lightbulb.BotApp( token='', default_enabled_guilds=(), prefix ="$", intents=hikari.Intents.ALL )

#

is there still a way to print it even if it is deffined in the variable?

hushed galleon
#

oh if you hardcoded the token then nevermind printing it

#

what you wrote there is a long string of random letters/numbers right

slow estuary
#

yeah

#

It was working fine before I changed it

hushed galleon
#

then maybe your script didnt update with the new token when you tried running it?

slow estuary
#

it isint a docker problem because it still breaks outside of docker

hushed galleon
#

oh ok

slow estuary
#

yeah thats what im thinking

slate swan
slow estuary
#

still doesn't work

nova stag
#

so i am trying to make it so that if a message is sent by a certain person it replies with something but i am getting this error

hushed galleon
#

@bot.event should be written without the parentheses, and also bot.send_message() is extremely outdated; text channels have a send() method so you would be writing await message.channel.send(...) there

nova stag
#

ok thanks

hushed galleon
#

oh and the IDs are represented as integers instead of strings

nova stag
hushed galleon
nova stag
junior verge
#

Just use ctx.send

hushed galleon
velvet tinsel
#

how would I get the ID of a recently created channel? I have the snippet of code await guild.create_text_channel("hello world"), but I would like to get the ID of it. How would I do that

hushed galleon
#

create_text_channel returns a TextChannel object, so you can access the .created_at property right afterwards

velvet tinsel
#

k thx

hushed galleon
#

oh wait, i dont know why i said .created_at

nova stag
#

hmmmmmm

velvet tinsel
#

i was confused lmao

#

I was looking at the docs and I was thinking this cant be right

hushed galleon
#

yea i just thought of it cause the created at time happens to be derived from the .id of the channel

velvet tinsel
hushed galleon
# nova stag

the on_message event only takes a Message object, so you should keep it as on_message(message)
(when you see ctx, its a conventional name used with message commands in discord.ext.commands)

#

you can do the same thing with the reply() method that the Message object has

nova stag
#

ok let me try

brave forge
#

please tell me how in discord.py do events and commands ?

#

that is, so that one in the file reads the other. Because event and commands don't work in the same file

#

@nova stag Can I help you ?

nova stag
sand dew
#

i am planning on making discord bots, should i use discord.py or hikari?

brave forge
#

@nova stag do you want to write to a certain participant in private messages ?

nova stag
supple thorn
#

Make the ping into a string and check it with the message content

nova stag
supple thorn
#

Yes

brave forge
#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
supple thorn
#

@nova stag what are you trying to do and whatโ€™s the error

nova stag
nova stag
supple thorn
#

Itโ€™s only message

#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

nova stag
supple thorn
#

Check if client.user is in message.mentions

supple thorn
unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your botโ€™s own messages and private messages are sent through this event. This can lead cases of โ€˜recursionโ€™ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
supple thorn
#

As you can see

nova stag
supple thorn
#

It only takes 1 positional argument which is message

nova stag
#

ok i get it now

nova stag
#

so what am i suppose to do now?

supple thorn
#

Remove author since it doesnโ€™t take that

winged bone
#

I think you should write if message.content == ping instead because if message == ping will compare the message object with a string which will always be False

#

because message will be a discord.Message object

#

@nova stag

nova stag
#

ok so i have achivied what i wanted by doing this

#

thanks for yall help

stone beacon
#

Noice

final iron
#

Why are you naming your id variable ping

nova stag
#

no particular reason

slate swan
regal flame
#

is there an event similar to on_ready that sends a message when the bot is stopped

regal flame
#

it didn't work when I tried it

#

I stopped the bot and received no message

surreal ruin
#

Anyone?

bitter perch
#

@regal flame you should subclass and override close

regal flame
#

what does that mean?

bitter perch
#
class MyClient(discord.Client):
  async def close(self):
    # call super().close and do your logic
regal flame
nova stag
cyan hare
#

help me pls

nova stag
nova stag
cyan hare
#

import commands

nova stag
cyan hare
#

so

#

what do i wrtie

nova stag
#

what are u trying to import

cyan hare
#

commands

#

import discord, random, aiohttp, asyncio
from discord import Webhook, AsyncWebhookAdapter
from discord.ext import commands
from discord.ext.commands import commands
from colorama import Fore as C
from colorama import Style as S

nova stag
cyan hare
#

then delete the 4 the line

short harbor
#

need help

cyan hare
#

or keep it

nova stag
#

from colorama import Fore, Style

nova stag
cyan hare
#

ok

#

it still an error

short harbor
#

how can i delet a messege sended with the bot ?

cyan hare
frozen patio
slate swan
frozen patio
#

I have to make new repl when I code with friends

nova stag
frozen patio
slate swan
nova stag
frozen patio
nova stag
frozen patio
#

Yeah

#

Repl just trash

#

ยฏ_(ใƒ„)_/ยฏ

nova stag
#

u shouldnt send your bot token like that in chat

#

i would suggest u to regenerate it

frozen patio
#

Itโ€™s not even the token

nova stag
#

someone can use it to take over ur bot

frozen patio
#

All tokens have an O at the beginning

nova stag
frozen patio
#

All my bots begin with O

#

And thatโ€™s like 20

nova stag
frozen patio
#

So yea they all start with O

nova stag
frozen patio
frozen patio
#

Itโ€™s already imported

nova stag
frozen patio
#

Yeah

regal flame
#

for the event on_message how do I get the channel that the message is sent in?

raw gate
#

on_message(ctx):
channel = ctx.channel

#

Or

#

channel: discord.TextChannel

slate swan
frozen patio
#

Yo thanks for using repl take our API timeout ๐Ÿ˜„

torn sail
slate swan
lapis meadow
#

Is it possible to have a bot send a picture. When the picture is sent it will have around 5 reactions added by the bot. I want it to be where the user can click 2 reactions and the combination will send a gif. Is this possible and if anyone knows how please help pls

frozen patio
#

Hmm

slate swan
raw gate
frozen patio
lapis meadow
#

Its definitely possible lol

raw gate
#

It is

lapis meadow
#

My bot does it but Iโ€™m lost along the lines of when the user reacts to two of the reactions and It sends a gif

frozen patio
#

5 separate emojis?

torn sail
#

Yes

raw gate
#

Yeah

frozen patio
#

Ohhhh I thought he meant 5 to 1 emoji ๐Ÿ˜…

lapis meadow
#

Iโ€™m assuming if I get the first down itโ€™ll be a whole bunch of elif statements

raw gate
#

Ah

lapis meadow
#

I have this right now:

#
    channel  = client.get_channel("CHANNEL_ID")
    if message.content.lower().startswith('experiment'): 
        moji = await message.channel.send("https://media.discordapp.net/attachments/955441795209236530/962094246314254437/unknown.png?width=480&height=612")
        emoji = ["\N{Large Yellow Circle}", "\N{Large Green Circle}", "\N{Large Blue Square}", "\N{Large Red Circle}", "\N{Large Blue Circle}"]
        for experiment in emoji:
            await moji.add_reaction(experiment)```
slate swan
lapis meadow
#

Well it'll send a link but the link will be a gif lol

#

Thanks a lot!!!

slate swan
raw gate
#

Where are the examples to discord.ui.modals

slate swan
#

idh the link at hand rn

raw gate
#

Okay ty

#

I think i have it

#

The link was in the discord py server as well i believe

raw gate
#

Oh ty

slate swan
raw gate
#

Tyty this helps sm

slate swan
raw gate
#

I got buttons down i just needed some help with modals and textinputs

lapis meadow
#
        moji = await message.channel.send("https://media.discordapp.net/attachments/955441795209236530/962094246314254437/unknown.png?width=480&height=612")
        emoji = ["\N{Large Yellow Circle}", "\N{Large Green Circle}", "\N{Large Blue Square}", "\N{Large Red Circle}", "\N{Large Blue Circle}"]
        for experiment in emoji:
            await moji.add_reaction(experiment)
    if user.reaction.emoji == "\N{Large Yellow Circle}" and "\N{Large Green Circle}":
        await message.channel.send("https://media.discordapp.net/attachments/957163963588681788/957164412807036928/yg.gif")```

I'm getting an error: "user" isn't defined. Does anyone know if I'm on any right track with making the bot send a gif if 2 reactions are clicked?
raw gate
#

Try user: discord.Member

#

or user = ctx.author

lapis meadow
#

Ahhh thx

#

lemme test hehehe

raw gate
#

I'm bad at helping lol I'm on my phone

#

And at work

lapis meadow
#

This is now the error:

#

line 57, in on_message
if discord.Member.reaction.emoji == "\N{Large Yellow Circle}" and "\N{Large Green Circle}":
AttributeError: type object 'Member' has no attribute 'reaction'

lapis meadow
#

Where do I put that? ;-;

raw gate
#

Oh yeahhh

lapis meadow
#

k might've got it

slate swan
# lapis meadow Where do I put that? ;-;

smth lile this

async def on_message(message):
    if message.content.startswith('$thumb'):
        channel = message.channel
        await channel.send('Send me that ๐Ÿ‘ reaction, mate')

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '๐Ÿ‘'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('๐Ÿ‘Ž')
        else:
            await channel.send('๐Ÿ‘')โ€Š
lapis meadow
#

ohhhh okay

#

So if I want to add two reactions I just put 'This' and 'That'

slate swan
#

....?

#

tbh i'll just get sleep, i havent slept for 3 days straight

lapis meadow
#

So like they need to react to two reactions in order for the bot to send the message

lapis meadow
lapis meadow
slate swan
#

I apologize for leaving while helping

lapis meadow
#

Nahhh you good hahah

regal flame
#

what can I do to make it so any message that is sent through DMs to my discord bot is sent to me through DMs

full lily
#

should be able to check if it's a dm with if message.guild is None

lapis meadow
#

Hey people! I'm having an issue with my bot. I want the bot to send an image with reactions. When the user clicks 2 of the reactions the bot will send a gif. I have 5 reactions total so there are a lot of combinations. The issue I have now is that the bot is able to send the image with the reactions but when I click the two reactions nothing happens... Here is my code if anything can help โค๏ธ

async def on_message(message):
    if message.content.lower().startswith('thumb'):
        channel = message.channel
        moji = await message.channel.send("https://media.discordapp.net/attachments/955441795209236530/962094246314254437/unknown.png?width=480&height=612")
        emoji = ["\N{Large Yellow Circle}", "\N{Large Green Circle}", "\N{Large Blue Square}", "\N{Large Red Circle}", "\N{Large Blue Circle}"]
        for experiment in emoji:
            await moji.add_reaction(experiment)

        def check(reaction, user):
            return user == message.author and str(reaction.emoji) == '\N{Large Yellow Circle}' and '\N{Large Green Circle}'

        try:
            reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
        except asyncio.TimeoutError:
            await channel.send('https://media.discordapp.net/attachments/957163963588681788/957164412807036928/yg.gif')```
#

*Not getting any errors

median kindle
#

Has anyone every had a issues where a discord bot changed your loggers os time?

#

(it is a very strange issue I am dealing with now)

nova stag
#

so if i use the on_message thingy
all other commands stop working why is that?

vagrant brook
#

Uhm you need bot.process_commands

#

!d discord.ext.commands.Bot.process_commands

unkempt canyonBOT
#

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

This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.

By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.

This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").

This also checks if the messageโ€™s author is a bot and doesnโ€™t call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.

Changed in version 2.0: `message` parameter is now positional-only.
unique yew
#

Hello SIr

#

Any one

#

I am creating discord sever joining script but when I send reqeuest with captcha key discord responsed that your captcha key required

cyan hare
#

can somone help me

#

what this mean

sick birch
# cyan hare

Can you post the full error? Parts of it are missing

pliant gulch
#

Looks like you have been banned from accessing the API

#

The little snippet you showed is the cloudflare stuff

sick birch
#

Usually when you start seeing HTML in your python errors, it's your cue to get off replit

pliant gulch
unique yew
#

Someone help me

cyan hare
#

okay

unique yew
slate swan
unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

Show full traceback

sick birch
#

Kind of difficult to tell what the issue is from a large chunk of seemingly random characters

slate swan
# cyan hare

Seems like you're getting ratelimited, try kill 1 in shell and restart the repl, sidenote: you'll keep facing this issue if you use replit

cyan hare
#

how do i try the kill 1

#

ahh in the shell

slate swan
pliant gulch
#

Defiently malicous

slate swan
#

Since bots can't join a server using invites

cyan hare
#

more errors

unique yew
slate swan
unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

unique yew
slate swan
#

the API doesn't allow bots to do that, that's for a normal user side.

unique yew
#

Okay

slate swan
#

even if you're doing it for a bot, that won't work
if you're doing that for a user, that's against ToS since automatic a user account in any way is not a good idea

frozen patio
slate swan
#

Actually, it depends more on your network system than your IDE, replit uses shared Ips so one of the user on that IP will let others get ratelimited too

frozen patio
#

Sadly

#

Just use VS code

pliant gulch
#

That is a valid option, albiet it isn't easy to setup

slate swan
pliant gulch
#

You have to make a request via PUT /guilds/guild_id/members/user_id

slate swan
#

So thats how this thing works ๐Ÿค”

pliant gulch
#

Yikes, quite the invasive bot

hollow badger
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

green bluff
sick birch
slate swan
#

๐Ÿ‘‹

#

Ded chat

frozen patio
#

That is good

#

Means people do not need help ๐Ÿ˜Ž

sick birch
#

Indeed

granite parcel
#
@bot.command()
async def me(ctx):
            member=ctx.author
            role = discord.utils.get("959611774498390127", id = "963371714606149644")
            for member in ctx.guild.members:
                if role in member.roles:
                    print('Supporters')    ```
#

bro this isnt working what is wrong with it

slate swan
granite parcel
#

yes

slate swan
#

mind showing your intents?

granite parcel
#

i show 1min

slate swan
#

sure

slate swan
# granite parcel i show 1min

oh i found the problem,
you are defining member as the author of the command and using member variable to iterate through the guild members, change one of their names, and discord.utils accepts an iterable as its first argument so you need to have the guild roles to iterate, and the id should be an integer

#

Why ppl use a var to define ctx.author :/

native wedge
#

member is already a thing, it just confuse

slate swan
#

Ye

#

@slate swan Can you not delete your messages?

granite parcel
slate swan
sick birch
slate swan
#

On ur code ig

buoyant zodiac
#

how do i get the white box?

sick birch
#

And unlike discord.js, IDs in python are integers, not strings

sick birch
buoyant zodiac
#

yes

sick birch
#

<t:UNIX_TIMESTAMP:FORMAT_CODE>

#

e.g <t:1649991837:F> => <t:1649991837:F>

slate swan
#

format code is optional though

#

Google unix timestamp creater

sick birch
#

I think "F" is default isn't it?

slate swan
sick birch
#

!d discord.utils.format_dt can help you format datetime objects

unkempt canyonBOT
#

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

This allows for a locale-independent way of presenting data using Discord specific Markdown...
buoyant zodiac
#
  await ctx.send(t)``` ????
#

it has to be in an embed or something?

buoyant zodiac
#

?

granite parcel
#
   await ctx.send(f"<t:{int(ctx.guild.created_at.timestamp())}>")```
buoyant zodiac
granite parcel
#

try now

slate swan
#

Bruh

slate swan
sick birch
#

But yes, that's how it should be done

#

Or, a more elegant solution would be to use discord.utils.format_dt()

granite parcel
#

?

sick birch
granite parcel
#

ohk

supple thorn
#

!d disnake.utils.format_dt

unkempt canyonBOT
#

disnake.utils.format_dt(dt, /, style='f')```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") for presentation within Discord.

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

Neat

granite parcel
#
@bot.command()
async def me(ctx):
    role_names = [role.name for role in ctx.author.roles]
    if "Voters" in role_names:
         await ctx.send('Hi')```
slate swan
#

?

granite parcel
#

this is working but can i make it universal like if author use this cmd anywhere where the bot is it gives the reply

supple thorn
#

It is already universal

granite parcel
supple thorn
granite parcel
#

no

#

it replies where the role exists

supple thorn
#

Don't you have to go through every guild the bot is in

#

And check if the role exists and in the author's roles

#

And if the author is in the same guild

slate swan
#

every server cannot have the same role unless the bot creates one

#

so its pretty much useless to do it

#

Hi Skev

supple thorn
#

Hello ashley

#

Ashley finally said hello to me first

slate swan
#
c = [member for member in guild.members for guild in bot.guilds if role in member.roles]```
idk if that works lmao (it shouldnt)
slate swan
slate swan
slate swan
#

but thats just 2 for loops

slate swan
#

thats not its syntax

#

lol didnt try

#

nor did I use list comps much anyway

#

Okimii change pfp day by day

boreal ravine
#

@slate swan go sleep

#

fail

slate swan
#

Yup

slate swan
unkempt canyonBOT
#

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

[54]
slate swan
#

๐Ÿ‘€

#

How tf 54 come

slate swan
#

!e

print([a for a in range(101) if a == 54])
unkempt canyonBOT
#

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

[54]
slate swan
#

which its just iterating through a list already

boreal ravine
slate swan
#

yes but

slate swan
#

Its just comparing?

slate swan
boreal ravine
#

it prints the list if the number is 54

slate swan
#

Oh i didnt see the print

#

xD

#

Lemme see something

#

Ok?

#

!e

a = 64
match a:
    case 63:
        print("lool")
    case 64:
        print("noo")
    case _:
        print("suii")
unkempt canyonBOT
#

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

noo
slate swan
#

Oh it works

#

..

#

lol

#

Thought that it didn't

#

Nice

#

Shush

boreal ravine
#

stop going offtopic

slate swan
#

Ok sir

#

.topic

lament depotBOT
#
**What's one feature you wish more developers had in their bots?**

Suggest more topics here!

slate swan
#

suiiii

#

Breh

boreal ravine
#

stop

slate swan
#

#bot-commands

boreal ravine
#

@slate swan @slate swan #bot-commands

slate swan
#

i havent done anything ๐Ÿ˜ณ

#

Yes oki is innocent

#

see

#

Voting began

boreal ravine
#

/ban

slate swan
#

๐Ÿ˜ณ

#

๐Ÿ’€lmao do yall add user commands to your bots?

#

Cause I don't really like them~

#

you guys have commands?

#

i use events๐Ÿ˜

#

Huh

#

you guys using Gateway?

slate swan
maiden fable
slate swan
slate swan
maiden fable
#

Uhh

slate swan
#

..

slate swan
#

smh hun๐Ÿ˜ก

#

but what if all I want to do is spam "hail okimi" in a channel, ๐Ÿ˜๐Ÿคฒ I'll just go for a rest client

#

๐Ÿ‘€

slate swan
#

because its not aimed at me

#

my name is okimii not okimi get it right yert

#

okay me

slate swan
maiden fable
#

Take this to an ot channel please

slate swan
#
import discord
from discord.ext import commands
bot = commands.bot(prefix="^")
@bot.command(name="spam")
async def okimii(ctx):
      while True:
           await ctx.send("hail okimi")
bot.run("*oahs9whhโ‚นjยฃร—*ร—9โ‚ฌ8hisosiw028293dndmxlzla0a9")
#

misspelled my name๐Ÿ˜”

#

*import

#

I do that usually, eval stuff

#

use semi colons and make it a one liner ๐Ÿ˜ณ ๐Ÿ˜

paper sluice
#
@(bot:=getattr(getattr(getattr(__import__('discord'),'ext'),'commands'),'bot')(prefix='^')).command(name='spam');async def okimii(ctx): [await ctx.send('hail okimi') for _ in iter(int, 1)];bot.run('token')
maiden fable
slate swan
polar ice
#

Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB

Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo

I've posted the actual loop itself. any help would be greatly appreciated.

Could it be because im using aysnc tasks

supple thorn
maiden fable
maiden fable
#

Yes

supple thorn
maiden fable
#

Don't go in there, unless u wanna start questioning your decision of learning Python

slate swan
#

Hi

supple thorn
slate swan
#

With ur skills

slate swan
#

Hi ded chat

neon oyster
#

How do i get my slash commands to work in one guild not global
discord.py 2.0

#

@ me plz

maiden fable
#

!custom-check

unkempt canyonBOT
#

Custom Command Checks in discord.py

Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:

from discord.ext.commands import check, Context

def in_any_channel(*channels):
  async def predicate(ctx: Context):
    return ctx.channel.id in channels
  return check(predicate)

This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).

The check can now be used like any other commands check as a decorator of a command, such as this:

@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
  ...

This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.

spring flax
#

can you make a custom on_message event where it only looks at message in one channel

maiden fable
#

Yea

#
@bot.event
async def on_message(msg):
    if msg.channel.id == ...:
        bot.dispatch("my_custom_on_message_which_listens_to_messages_only_in_one_channel", msg)
    await bot.process_commands(msg)
spring flax
#

is there a way to nnot check channel id in the event itself?

maiden fable
#

Wym

maiden fable
#

Internals

spring flax
#

so should i be using that?

maiden fable
#

Yea

spring flax
maiden fable
#

Uh

spring flax
maiden fable
#

Not sure

neon oyster
#

in discord.py lib how do i enable a slash command from a cog

mortal dove
#

How do I tell discord that I have seen the interaction? When someone presses a button, the command does all it needs to do, but still says that the interaction failed because I never responded to that interaction.

mortal dove
slate swan
#

๐Ÿค” may i have a look at the code?

mortal dove
#
    @discord.ui.button(
        label = "L",
        style = discord.ButtonStyle.green,
        row = 0
    )
    async def leftTrigger(self, interaction: discord.Interaction, button: discord.ui.Button):
        pyautogui.keyDown("A")
        await asyncio.sleep(0.2)
        pyautogui.keyUp("A")
        embed = fmte(
            ctx=self.ctx,
            t="Playing: Pokemon: Fire Red",
            d="For: {} minutes".format((time.time() - self.ctx.start_time) / 60)
        )
        pyautogui.screenshot().save("pyauto_resources/game_image.jpg")
        file = discord.File("pyauto_resources/game_image.jpg", filename = "Game_Image.jpg")
        await interaction.message.edit(embed=embed,attachments=[file,],view=VBA_View(self.ctx,self.bot))
``` Each message has 9 buttons. When a button is pressed, the message changes to new game frame and new time log.
#

Nothing is said to the user

slate swan
mortal dove
#

yeah I want to tell discord to not expect anything

#

and that the interaction is complete

slate swan
#

hmm

#

then ig u can do something likeee...

mortal dove
#

btw I know that I can use self.ctx.defer(), but that just keeps the interaction going forever, which isn't what I want

slate swan
#

then..on timeout, u can edit the embed, by sending the 'view' again

#

it'll be a new interaction.. but for the user it'll be just like an edit message..

mortal dove
#

I could, but I just think it's much more clean to edit. If I find no other solution, then sure I'll do that.

slate swan
#

welll.. tias :'/

eternal apex
#

I'm trying to make a music bot but this happened. Can anyone help me?

vocal snow
#

!d discord.ext.commands.Context.voice_client

unkempt canyonBOT
#

property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
tired hinge
#

i've used asyncPRAW to make sure that my meme command will be asynchronous, but it doesn't appear to be so. when i run the meme command, it takes a few seconds and then sends the meme. if i try to run any commands in those few seconds, it does not respond to them.

reddit = asyncpraw.Reddit(
client_id=db["reddit_id"],
client_secret=db["reddit_secret"],
user_agent=db["reddit_agent"],
username=db["reddit_username"],
password=db["reddit_pwd"]
)



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

    @commands.command(name="meme", description="Sends you a meme. Default subreddit is r/memes. You can also specify a subreddit.")
    @commands.cooldown(1, 6, commands.BucketType.user)
    async def memeFromReddit(self, ctx, subreddit="memes"):
        
        try:
            subreddit = await reddit.subreddit(subreddit, fetch=True)
            if subreddit.over18:
                await ctx.send("ohoho you sneaky little bastard, that's an nsfw subreddit")
                return
            subs = []
            async for submission in subreddit.hot(limit=30):
                subs.append(submission)
            sub = random.choice(subs)
            while True:
                if sub.id not in db['usedSubs'] and sub.is_reddit_media_domain and not sub.is_video and not sub.over_18:
                    break
                elif sub in oldSubs:
                    sub = random.choice(subs)
                    
            memebed = discord.Embed(title=sub.title)    
            memebed.set_image(url=sub.url)
            memebed.set_footer(text=f"r/{sub.subreddit}")
            oldSubs.append(sub)
            db['usedSubs'].append(sub.id)
            await ctx.send(embed=memebed)
        except:
            await ctx.send("couldn't get your meme. sorry!")
static epoch
#

there's a chance that your while loop is freezing the entire thing?
you might want to also check if any of the properties you're getting are making extra requests

polar ice
#

Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB

Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo

I've posted the actual loop itself and also the first function. any help would be greatly appreciated.

Could it be because im using aysnc tasks

bleak karma
#

is there a way to make a command set an embed colour? (i already made the db)

like

!embed set color ffffff

im using

emb = discord.Embed()
emb.description="<< **This is how the color looks like**"
emb.colour = "0x" + value
await ctx.send(embed=emb)

but it gives an error:

Ignoring exception in command e_embed edit:
Traceback (most recent call last):
  File "/home/runner/ganyubot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/runner/ganyubot/commands/embed.py", line 164, in edit
    emb.colour = "0x" + value
  File "/home/runner/ganyubot/venv/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour
    raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__)
TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
inner epoch
#

Am facing a strange issue I have a bot which has some NSFW commands on a particular server it is serving those commands in SFW channel while on every other it aint

placid skiff
#

nsfw commands are allowed only in NSFW channels

bleak karma
#

oh its not

placid skiff
#

it is of course

#

but not like you did

bleak karma
#

oh, how though/

placid skiff
#

read the error D_D

supple thorn
#

Blvck not having it today

placid skiff
#

so...? it is not hard to guess it is literally written D_D

bleak karma
#

im still learning

placid skiff
#

bruh it's not like intelligence or something is basic python, basic like the lowest level possible D_D

bleak karma
#

i mean i understand the error

placid skiff
#

TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.

#

Embed.colour takes as type Union[discord.Colour, int, Embed.Empty]
You are assign it to a string

#

if your use discord.Colour, you can set an RGB value

#

!d discord.Colour

unkempt canyonBOT
#

class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").

There is an alias for this called Color...
placid skiff
#

Embed.colour = discord.Colour(255,255,255) for example shall return white

bleak karma
#

oh makes sense now

lofty pecan
#

Hi there, just looking for tips, I am currently moving from json to sqlite3, and after adding a connect and a cursor in my on_ready I realized that if I put a value guild_id and then my other values it will just put everything on the same row. Would there be a way to create some kind of bag inside my table for a specific guild?

placid skiff
#

for every guild insert a new row D_D

lofty pecan
#

yeah but that would mean every thing will just be in the same main table isn't that bothering ?

#

(I haven't done SQL in 3 years so it's hard)

slate swan
#

create a new table for every guild ๐Ÿคทโ€โ™‚๏ธ

lofty pecan
#

yeah I thought about that as well

#

I was just wondering if there was a way to centralize everything in the same main file and then make subtable inside

slate swan
#

i was just suggesting

lofty pecan
#

because I am using the connect command in the on_ready in my events cog, so I don't see a way to get the guild_id other than adding a ctx argument inside which seems weird for that function

slate swan
#

but new a table for every server

#

srsly?

#

thats like such a bad use of memory

placid skiff
lofty pecan
#

Yeah I wouldn't try using sqlite if I had to do that

slate swan
#

okay okay, iโ€™m sorry if my suggestion isnโ€™t as good as yours

slate swan
slate swan
placid skiff
#

Bro database are used to store dataset which refers to the same object (alias a same set of data)
there is absolutely no sense to create different table for every guild

lofty pecan
#

So if I put everything inthe same file and then just do a FROM main SELECT guild_id it should work just fine ?

placid skiff
#

plus it will be a really mess

slate swan
#

ok

slate swan
lofty pecan
#

oki

placid skiff
#

easy as that D_D

lofty pecan
#

ho god not that

#

I have fragment of memories about that

slate swan
#

......?

#

I mean, every normal individual does that

placid skiff
#

lol

lofty pecan
#

I haven't done sql in 3 years I don't remember most of it

maiden fable
#

I never understood how to set primary and foreign keys ๐Ÿฅฒ

lofty pecan
#

๐Ÿฅบ

slate swan
#

๐Ÿ‘‹

maiden fable
lofty pecan
#

o_O

slate swan
lofty pecan
#

-_-