#discord-bots

1 messages · Page 947 of 1

boreal ravine
#

And GuildID =

twin flower
#

ok

boreal ravine
#

Also, don't use f-strings inside of queries

slate swan
#

thanks, it works

twin flower
#

The balance command says "database is locked" when trying to check values

#

it can't add them if they aren't there for some reason

pliant gulch
#

Yes, but it makes no sense to use run.

#

If your using an async driver for your database as I've said earlier

#

You will need an async call to connect

#

You'd use run for a sync driver

spring flax
#

okay so I saw that connect and start are coros so either would work

pliant gulch
#

But I will specifically recommend start

#

connect is where discord.py does some important stuff

#

And that's where the exponential backoff is

#

It would be a lot safer to do it in start

supple thorn
twin flower
#

My thing is saying that my database is locked, any help? using aiosqlite module

pliant gulch
#

Not much

#

login calls setup_hook and login is inside of start

#

It's basically the same thing except you don't override the two calls in start discord.py does

#

Which is calling upon login then connect

#

I would just make a bound method to your class that syncs

#

Then call it whenever you need to update a command

#

You can however do it automatically, but of course that means using extra bandwith every time you start your bot

#

And also means you use a request for X command at the start

#

It can probably put some stress on the API, if a lot of people do it

pliant gulch
#

Yep, then what I says apply

#

You could make a "smart" sync

junior verge
#

Anyone?

pliant gulch
#

But that's a bit harder

#

And I cba to explain right now

supple crescent
#

this is my current code, i just dont know how to make it so its only scanning a certan channel

@bot.event
async def on_message in <945861044163731476> (message):
    await message.delete()
pliant gulch
#

Can't be assed

junior verge
#

How do you if its possible

regal pulsar
#
@bot.command()
@commands.check_any(commands.has_permissions(administrator=True), commands.has_permissions(ban_members=True))
async def ban(ctx: commands.Context, user: discord.User):
    await ctx.guild.ban(user)
    await ctx.channel.send(f"{user.mention} has been banned.")


@ban.error
async def on_ban_error(ctx, error):
    if isinstance(error, commands.BotMissingPermissions):
        await ctx.channel.send("I cannot ban the owner.")
    if isinstance(error, commands.CheckAnyFailure):
        await ctx.channel.send("You Don't Have Perms Dumbass")
#

why isnt this error handler working

#

i get no error message in the channel

slate swan
#
@bot.command()
async def testing123(ctx, userid):
    with open("/root/Textfiles/changelog_ids.txt", "a") as f:
        f.write(f"{userid}\n")
        f.close()

This is my code, why doesnt it write in the file?

slate swan
slate swan
regal pulsar
#

i see

slate swan
#

another error too

#

it should be like this

@commands.has_permissions(ban_members=True)

not:

commands.has_permissions(ban_members=True))
slate swan
#

you need to close an opening bracket

slate swan
slate swan
twin flower
#

Getting some strange error when trying to do a warn command. Says corountine is not subscriptable. I don't know what this means and looking for some help?

slim ibex
#

Let’s see the code

#

You are trying to subscript a coroutine somewhere

#

eg: await foo()[index] probably

slate swan
#

you oughta declare it to a variable and subscript that

twin flower
#

yeah i forgot an await, got it working but now it's saying that the database is locked.

#

Doesn't do it with other db-related commands tho

misty stream
#

did i get tagged ?

#

cause i couldnt find it anymore

hasty stump
#
@client.event
async def on_member_join(member):
    channel = client.get_channel(957288621424119828)
    embed = nextcord.Embed(colour= nextcord.Colour.blue(),title=f"{member}",timestamp=datetime.datetime.utcnow())
    embed.add_field(name="Thank you for joining",value="\nMake sure to check \n•[#957061610139189288](/guild/267624335836053506/channel/957061610139189288/) \n•[#957061610139189288](/guild/267624335836053506/channel/957061610139189288/) \n•[#957061610139189288](/guild/267624335836053506/channel/957061610139189288/)",inline=False)
    embed.set_thumbnail(url=member.avatar.url)
    embed.set_footer(text="Enjoy your stay :3")
    await channel.send(f"**Welcome into the server ~ {member.mention}!**")
    await channel.send(embed=embed)```
slate swan
slate swan
slate swan
slate swan
#

i think.

#

i never got it working either, but thats what u have to do

hushed galleon
#

well, the intents you pass should have .members enabled

slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. 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.

slate swan
slate swan
hasty stump
slate swan
unkempt canyonBOT
#

property display_avatar: nextcord.asset.Asset```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
slate swan
#

Use that instead.

#

member.display_avatar.url

hasty stump
hasty stump
slate swan
hasty stump
#

hm working

slate swan
#

!d nextcord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar: nextcord.asset.Asset```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
hasty stump
#

thanks

slate swan
slate swan
#

When does 6G come?

slate swan
slate swan
slate swan
hybrid mural
#

@slate swan

#

you know mysql right?

#

or was that someone else

slate swan
hybrid mural
#

alright so lets say

slate swan
#

hm?

hybrid mural
#
CREATE TABLE IF NOT EXISTS exp (
    UserID integer PRIMARY KEY,
    FISH integer DEFAULT 0,
    Level integer DEFAULT 0,
    XPLock text DEFAULT 100


);

this is my sql file

slate swan
#

hm

#

it is always ideal to set the IDs to be NOT NULL too

UserID INTEGER PRIMARY KEY NOT NULL,
hybrid mural
#

basically just UserID for the user, how many fish they have(a mini game like who has the most fishes) Level blabla

slate swan
#

hm?

hybrid mural
#

now this is the py file:

from os.path import isfile
from sqlite3 import connect

DB_PATH = "./db/database.db"
BUILD_PATH = "./db/build.sql"

cxn = connect(DB_PATH, check_same_thread=False)
cur = cxn.cursor()

def with_commit(func):
    def Inner(*args, **kwargs):
        func(*args, **kwargs)
        with_commit(func)
    return Inner

@with_commit
def build():
    if isfile(BUILD_PATH):
        scriptexec(BUILD_PATH)

def commit():
    cxn.commit()

def close():
    cxn.close()

def field(command, *values):
    cur.execute(command, tuple(values))
    if(fetch := cur.fetchone()) is not None:
        return fetch[0]

def record(command, *values):
    cur.execute(command, tuple(values))
    return cur.fetchone()

def records(command, *values):
    cur.execute(command, tuple(values))
    return cur.fetchall()

def column(command, *values):
    cur.execute(command, tuple(values))
    return [item[0] for item in cur.fetchall()]

def execute(command, *values):
    cur.execute(command, tuple(values))

def multiexed(command, valueset):
    cur.executemany(command, valueset)

def scriptexec(path):
    with open(path, "r", encoding="utf-8") as script:
        cur.executescript(script.read())

So basically how do i implement that a specific user id gets their "FISH" added 1

#

i probably have to do it in the python file right

slate swan
#

fie fie

#

this is so so complicated fie fie

#

nvm

slate swan
#

to add a fish to them

hybrid mural
#

Update how

slate swan
#

sqlite3 will be blocking your bot

hybrid mural
#

Damn aight

slate swan
#
execute('UPDATE table_name SET FISH = ? WHERE UserID = ?', fish_amount, user_id)

this will work
if you use aiosqlite
add an await since you'd be making an asynchronous function

hybrid mural
slate swan
#

yeah and?

hybrid mural
#

Basically DB.execute()

slate swan
hybrid mural
#

Y doe

hybrid mural
#

Yes

slate swan
#

I used execute function in context to that

hybrid mural
#

Ah so i update the execute file to that

slate swan
hybrid mural
#

Ah nvm

#

I get it

slate swan
#

quick learner

modern fiber
#

How do I find my discord bot's token now.. bruh

#

the new update sucks lmfao

hushed galleon
#

you regenerate it from the bot tab in your application page

cold sonnet
#

guys I'm leaving discord

misty stream
#
streamer = member.activities[0].url.split("/")[-1]
List = [streamer]
CurrentFeatured = random.choice(List)
await ctx.send(CurrentFeatured)
empty = False

i am getting the members who are streaming but if there are more i want to get a random streamer i tried using a list and getting a random choice but its not working i am doing something wrong can someone help me out ?

light violet
#

How to set jishaku for some selected people use only

#

Does anybody know it?

supple thorn
hushed galleon
slate swan
#

Back

sturdy raven
#
try:
   reply = await self.bot.wait_for("message", check=check, timeout=20)
except asyncio.TimeoutError:
   await choice.edit(content="Train left the station.")
   return

Command raised an exception: NameError: name 'asyncio' is not defined

hushed galleon
#

that means you have to import the asyncio module

sturdy raven
#

import asyncio?

hushed galleon
#

yes

cold sonnet
jade jolt
#

lmao

slate swan
#

if a user sends a command how to wait for an user confirmation with emojis?

polar plinth
#

welp

#

here error

latent ember
#

I need an unban command

#

my current one isint working

torn sail
latent ember
#
@discord.ext.commands.has_role(959430769086959646)
async def unban(ctx, *, member):
  banned_users = await ctx.guild.bans()
  member_name, member_discriminator = member.split ('#')

  for ban_entry in banned_users:
    user = ban_entry.user

    if (user.name, user.discriminantor) == (member_name, member_discriminator):
      await ctx.guild.unban(user)
      await ctx.send(f'Unbanned  {user.mention}')
      return```
torn sail
#

!d discord.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
latent ember
torn sail
#

user: discord.User in function args

latent ember
#

i dont understand which part i need to change 😄

#

@torn sail im confused

hybrid mural
#

does random.randrange include the start and stop or exclude

slate swan
#

uhh

#

does anyone know how to timeout ?

heavy folio
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
heavy folio
#

!d discord.Member.timeout this works too

unkempt canyonBOT
#

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

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

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

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

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

misty sluice
#

help

pliant gulch
#

Involves modifying the decorator which does a database lookup to check for differences, then if different sync command when registering

#

This makes it so it doesn’t auto sync ALL commands on runtime

#

Only those that have been modified

urban shell
#

hey, is anyone familiar with pycord here

latent ember
#

How to make a command to clear messages

slate swan
unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
dull terrace
#

are tags unique in discord?

#

combinations of username + discriminator

latent ember
dull terrace
#

thank

urban shell
# latent ember How to make a command to clear messages
import discord
from discord.ext import commands

client = commands.Bot(command_prefix= "PREFIX", activity=activity)

@client.command(pass_context = True)
async def clear(ctx, number):
    mgs = [] #Empty list to put all the messages in the log
    number = int(number) #Converting the amount of messages to delete to an integer
    async for x in client.logs_from(ctx.message.channel, limit = number):
        mgs.append(x)
    await client.delete_messages(mgs)

client.run('TOKEN')
quaint epoch
#

you don't need to pass context in the rewrite

#

The aztecs recognize this code more than i do

#

and also, put a permissions check

cold sonnet
#

wtf

#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
cold sonnet
#

made for use

latent ember
cold sonnet
#

you get the channel and use the purge method on it

#

with limit being the amount of messages you wanna purge

maiden fable
cold sonnet
#

I'm never gonna be toxic to anyone cuz that's bad

#

and meh not bad

urban shell
#

xDD

latent ember
#

i dont understand can you help me make the command?

urban shell
#

I've never worked on a delete messages command before

#

but you can always refer the docs

cold sonnet
#

sure, do you wanna clear messages in the channel the command's invoked in?

urban shell
#

or SO

cold sonnet
#

what's so

urban shell
#

Stack Overflow

cold sonnet
#

o

latent ember
#

im not sure how to make discord bot stuff yet

#

my first bot im makin

cold sonnet
#

you know how to start making a command?

#

Ashley writing a book

slate swan
# urban shell I've never worked on a delete messages command before
@command
@commands.has_permissions(manage_messages=True)
async def clear(ctx: commands.Context, amount: int, channel: discord.TextChannel=None):
  if amount > 200:
    return await ctx.send("too many messages", delete_after=20)
  channel = channel or ctx.channel
  await channel.purge(limit=amount)
  await ctx.send(f"cleared the messages in {channel.mention}")
cold sonnet
#

ew

latent ember
slate swan
cold sonnet
#

you're just an ew Ashley

latent ember
#

i have made

urban shell
slate swan
latent ember
#

some commands already

cold sonnet
#

how is he gonna learn from spoonfeed 😠

slate swan
urban shell
slate swan
#

bye

cold sonnet
#

nah u did it u explain

#

eat what u made Ashley

placid skiff
#

what is this sh*t talkin? D_D

maiden fable
#

stop with the drama

regal pulsar
maiden fable
regal pulsar
#

im pretty sure thats right

maiden fable
#

Yes

urban shell
placid skiff
regal pulsar
placid skiff
#

1 day D_D

cold sonnet
#

oof

placid skiff
#

i've learnt d.py in less than a week, then learned slash commands and other interaction in disnake in few days D_D

regal pulsar
#

it was exam month 💀

latent ember
#

now it works

regal pulsar
#

finals

#

oh yeah i actually do have a question

#

if i wanted to make a levelling bot

maiden fable
regal pulsar
#

how would i go about the database

maiden fable
cold sonnet
#
#define command
@bot.command()
#check for manage_messages permission
@commands.has_permissions(manage_messages=True)
#command name, taking ctx as always, an amount that has to be a number, otherwise error, and a channel that can be none
async def clear(ctx: commands.Context, amount: int, channel: discord.TextChannel=None):
  #if the number's too low
  if amount > 200:
    #stop and send that's too many, message deleted after
    return await ctx.send("too many messages", delete_after=20)
  #channel stays the same or it will be the channel the command's invoked in
  channel = channel or ctx.channel
  #purge the amount of messages you wrote in the command
  await channel.purge(limit=amount)
  #send that it was cleared
  await ctx.send(f"cleared the messages in {channel.mention}")
regal pulsar
#

i mean

cold sonnet
#

overcommenter yes

regal pulsar
#

id be using mongo

#

but

placid skiff
#

if you never used a db before use sqlite (builtin database in python) with aiosqlite package

regal pulsar
#

if i need to make everyones stats unique per guild

#

how would i do that

latent ember
#

@cold sonnet do you know how to make the bots message delete after saying messages cleared

regal pulsar
#

then delete

cold sonnet
#

delete_after kwarg

regal pulsar
#

oh

#

didnt know that existed

cold sonnet
#

example in the return await one above

regal pulsar
#

i just did something like msg = await ctx.channel.send(embed=embed)

#

then msg.delete() i think

cold sonnet
#

ctx.send better

regal pulsar
latent ember
#
from discord.ext import commands
from webserver import keep_alive
import os

client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    print('Bot is ready.')

@client.event
async def on_member_join(member):
    channel = client.get_channel(959102280731361302)
    embed=discord.Embed(title="Welcome!",description=f"{member.mention} Just Joined")
    await channel.send(embed=embed)

@client.event
async def on_member_remove(member):
    print(f'{member} has left an server.')

@client.command()
async def ping(ctx):
    await ctx.send(f'ping is '+str(round(client.latency * 1000))+'ms')


@client.command()
@discord.ext.commands.has_role(959430769086959646)
async def kick(ctx, member : discord.Member, *, reason=None):
  await member.kick(reason=reason)
  await ctx.send(f'Kicked {member.mention}')
  

@client.command()
@discord.ext.commands.has_role(959430769086959646)
async def ban(ctx, member : discord.Member, *, reason=None):
  await member.ban(reason=reason)
  await ctx.send(f'Banned {member.mention}')

@client.command()
@discord.ext.commands.has_role(959430769086959646)
async def unban(ctx, *, member):
    banned_users = await ctx.guild.bans()
    
    member_name, member_discriminator = member.split('#')
    for ban_entry in banned_users:
        user = ban_entry.user
        
        if (user.name, user.discriminator) == (member_name, member_discriminator):
             await ctx.guild.unban(user)
             await ctx.channel.send(f"Unbanned: {user.mention}")


@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx: commands.Context, amount: int, channel: discord.TextChannel=None):
  if amount > 200:
    return await ctx.send("too many messages", delete_after=20)
  channel = channel or ctx.channel
  await channel.purge(limit=amount)
  await ctx.send(f"cleared the messages in {channel.mention}")```
#

this is my bot rn

#

how to make the latest command or all the commands messages delete automatically after a short time?

regal pulsar
#

uh

#

maybe something like

cold sonnet
#

I think you'd have to put delete_after x in every send

regal pulsar
#

can you iterate through messages in a channel?

cold sonnet
#

or (just something you won't do, neither will I)
subclass context and make your commands return ctx as that subclass
in that subclass, change the send function to having a default delete_after

#

there has to be an easier way

#

like commands.Context.send.delete_after = 5
(won't work don't try, just an example)

slate swan
slate swan
#

it's literally the same as ctx.channel.send

regal pulsar
cold sonnet
slate swan
#

who

cold sonnet
#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
regal pulsar
#

i see

#
@bot.command()
async def purge(ctx, member: discord.Member):
    async for channel in ctx.guild.channels:
        async for msg in channel.history(limit=100):
            if msg.author == member:
                msg.delete()
#

something like this then?

slate swan
#

you realize that

regal pulsar
#

member would be the bot in his case

slate swan
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to delete messages even if they are your own. The [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
slate swan
#

is a thing

regal pulsar
#

yeah

#

he wants to delete messages by the bot

slate swan
#

and you can just pass it a lambda check that checks if message.member = member

slate swan
regal pulsar
#

oh

#

well didnt know that logo_stack_overflow

#

oh yeah so

#

if i were to make a levelling bot

slate swan
#
def check(m):
  return m.author = member

await channel.purge(limit=100, check=check)```
#

should do the trick

regal pulsar
#

where users have a profile in each guild

#

how would i do that with something like mongo

#

but does anyone know

slate swan
#

me when i forget how to use lambda

regal pulsar
slate swan
#

you need a document just to store which members belong to which guild

#

and then several pointers for each member in the guild

regal pulsar
#

hmm

slate swan
#

it's something worth opening a discussion somewhere else about

regal pulsar
#

that is complicated

slate swan
#

because it'll get a little complicated

regal pulsar
#

thanks

slate swan
#

the people in #databases will probably laugh at your face

#

for not using their holy sqlite database types

#

still, good luck

slate swan
#

they're mean sadge

regal pulsar
#

ill probably end up learning sqlite

#

i need it to join my school's it council

#

need to learn django too

hybrid mural
#

whats the equal to cursor.execute in aiosqlite

boreal ravine
hybrid mural
#

nvm seems like ive done something wrong

boreal ravine
#

being rude isn't tolerated here lmao

slate swan
#

who cares kayle, i was just joking

regal pulsar
#

lol

boreal ravine
regal pulsar
#

i forgot to learn lambda shipit

boreal ravine
#
def main():
    print(1):
``` is the same as ```py
lambda: print(1)
slate swan
#

i know what a lambda function is

regal pulsar
#

uh

sick birch
#

wait_for paired with a check

#

The check is the most important part

regal pulsar
sick birch
#

Make sure the sent message is in a dm

boreal ravine
#

Use the wait_for method, and get the file by doing ```py
message = wait_for(..., ...)
message.attachments

sick birch
boreal ravine
#

Well robin that is why I used ellipsis

sick birch
#

Return true if:
- the message is from the person who used the command
- the message contains an attachment
- the message is in a DM

hybrid mural
#
Traceback (most recent call last):
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\leka\PycharmProjects\Amk\fishergame_cog.py", line 15, in getfish
    await db.execute("UPDATE exp SET FISH = ? WHERE UserID = ?", ran, alpha)
  File "C:\Users\leka\PycharmProjects\Amk\db.py", line 48, in execute
    await cur.execute(command, tuple(values))
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
AttributeError: 'Result' object has no attribute 'execute'

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

Traceback (most recent call last):
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 923, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 196, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Result' object has no attribute 'execute'

So im testing out a db with aiosqlit eand ive got this error

boreal ravine
#
def check(message):
    ...
``` or ```py
lambda message: ...
``` `...` being the stuff you need to check for
hybrid mural
#

hold on ill send the other ocmmands

boreal ravine
#

No

hybrid mural
#

?

boreal ravine
regal pulsar
#

oh yeah they have that filter thing now

#

i opened it and got this 3d glasses one that blinded me

hybrid mural
#

i assume theres a difference from mysql(outside of the await and async functions) in aiosqlite with cursors?

#

ill ask in databases

boreal ravine
#

👍

quaint epoch
#

yay, finally made a reminder system for my bot

#

that DOESN'T use asyncio.sleep

#

btw can text commands have keyword args? like !mute reason="loser" member=879807617260716143

covert swan
#

Please help me set up the command
@client.command
async def cash(ctx, member: discord.Member):
print('cash')
cash = cursor.execute("SELECT cash FROM economy WHERE id = ?".format(member.id)).fetchone()[0]
member = discord.Member
await ctx.send("Показатель HP" + member + "составляет" + cash)

slate swan
#

You know @unkempt canyon's !eval command, any easy way to create one like it?

covert swan
#

!eval

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!eval <code>
Can also use: e

*Run Python code and get the results.

This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.

We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*

slate swan
sick birch
#

Yeah, alternative to nsjail

slate swan
#

Do you have a link?

sick birch
slate swan
#

Thanks!

sick birch
#

or, if you want something else, try nsjail by google (i think)

covert swan
#

@sick birchCan you please help?

sick birch
#

with what?

slate swan
sick birch
#

Personally, not sure. I haven't used piston

#

I only did code execution once by spinning up a docker container which is inefficient

covert swan
#

@sick birchI can't make a command to work
@client.command
async def cash(ctx, member: discord.Member):
print('cash')
cash = cursor.execute("SELECT cash FROM economy WHERE id = ?".format(member.id)).fetchone()[0]
member = discord.Member
await ctx.send("Деньги" + member + "is" + cash)

sick birch
#

Read their documentation and get it from there

slate swan
sick birch
sick birch
covert swan
sick birch
#

What variable?

covert swan
#

@sick birchcash = cursor.execute("SELECT cash FROM economy WHERE id = ?".format(member.id)).fetchone()[0]

sick birch
#

You're aware you're supposed to be using aiosqlite?

covert swan
gaunt ice
#

typing...

#

are u done lol

open talon
#

@sick birch Can you help me with some kinda paging-bot?
i was trying with the code on stackoverflow, but doesn't works for me

(https://stackoverflow.com/questions/61787520/i-want-to-make-a-multi-page-help-command-using-discord-py)

light violet
#

!jsk py 1+1

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.

radiant wing
#

My bot uses global variables in order to work. How do I make it have different global variables for different users?

#

Without rewriting much code

cold sonnet
#

why not bot variables

#

to transfer through cogs and such

#

and not having to use global everytime

slate swan
#

and global variables for each user?

cold sonnet
#

dicts goated

slate swan
#

rip

hybrid mural
#

@slate swan you came right on time

#
Ignoring exception in command fish:
Traceback (most recent call last):
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\leka\PycharmProjects\Amk\fishergame_cog.py", line 15, in getfish
    await db.execute("UPDATE exp SET FISH = ? WHERE UserID = ?", ran, alpha)
  File "C:\Users\leka\PycharmProjects\Amk\db.py", line 48, in execute
    await cur.execute(command, tuple(values))
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
AttributeError: 'Result' object has no attribute 'execute'

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

Traceback (most recent call last):
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\bot.py", line 1234, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 923, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\leka\PycharmProjects\Amk\venv\lib\site-packages\discord\ext\commands\core.py", line 196, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Result' object has no attribute 'execute'

help

#

i assume Result is the cursor

maiden fable
#

show yr init

#

Result is the class name, not the cursor

hybrid mural
maiden fable
#

the init of the Result class

hybrid mural
#

ah

dry kelp
#

how can i add this item in a certain row?

cold sonnet
#

HelpSelect is a select menu?

slate swan
#

rip

cold sonnet
#

yeah prolly

dry kelp
#

yep

cold sonnet
#

what u ripping

dry kelp
#

??

cold sonnet
#

!d discord.ui.View.add_item

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

This function returns the class instance to allow for fluent-style chaining.
dry kelp
#

i got this error so i tryna move it to row 1

#

the dropdown

hybrid mural
cold sonnet
#

u got this error on this line

fierce sonnet
#

heyhey could anýone help me with a unban command i really ran out of ideas how i could do it

maiden fable
#

self.bot.db.execute

hybrid mural
dry kelp
cold sonnet
#

there are no dropdown lines

maiden fable
#

prolly

cold sonnet
#

try adding them in a different order

dry kelp
#

i will just set the dropdown to row 1 and that's it

#

fuck it

junior verge
#
@client.command()
async def nowplaying(ctx: commands.Context):
    if not ctx.voice_client:
        return await ctx.send("Your not playing any music")
    elif not getattr(ctx.author.voice, "channel", None):
        return await ctx.send("Join a voice channel first")
    else:
        vc: wavelink.Player = ctx.voice_client

    if not vc.is_playing(): 
        return await ctx.send("Nothing is playing")
    
    em = discord.Embed(title=f"Now playing: {vc.track.title}", description=f"Artist: {vc.track.author}")
    em.add_field(name="Duration", value=f"`{str(datetime.timedelta(seconds=vc.track.lenght))}`")
    em.add_field(name="Extra Info", value=f"Song URL: [Click Me]({str(vc.track.uri)})")
    return await ctx.send(embed=em)

``` Is anything wrong with this? When I run this command it returns me nothing and shows no error
sick birch
#

use the tasks extension to run something every X hours

junior verge
#

idk I just did that

sick birch
#

If it shows no error you probably have an error handler somewhere eating it

#

look for on_command_error anywhere

latent ember
#

How to make the bot filter some words?

junior verge
# sick birch look for `on_command_error` anywhere

yeah look: ```py
@client.event
async def on_command_error(ctx,error):
if isinstance(error, commands.CommandInvokeError):
error = error.original

if isinstance(error, commands.MissingPermissions):
    em = discord.Embed(title='![cross](https://cdn.discordapp.com/emojis/956904380148371476.webp?size=128 "cross") Error', description=f"{ctx.author.mention}, You don't have the permissions to do this.", color=0xCC1313)
    await ctx.send(embed=em)
elif isinstance(error, commands.MissingRequiredArgument):
    em = discord.Embed(title='![cross](https://cdn.discordapp.com/emojis/956904380148371476.webp?size=128 "cross") Error', description=f"{ctx.author.mention}, You are missing arguments.", color=0xCC1313)
    await ctx.send(embed=em)
sick birch
#

There we go

junior verge
sick birch
#

It's eating up all your errors

junior verge
#

Oh

sick birch
#

Putting words in my mouth haha

junior verge
#

Uhm

pliant gulch
#

Wave link 👁️👁️

junior verge
#

oops

#

uhm okay but whats wrong in my error handler?

sick birch
#

It ignores all errors that are not what you want

junior verge
#

How do I get that fixed?

sick birch
#

basically your error handler does this:
if error is of type X,
do this
else if error is of type Y,
do this
else the error is something else,
ignore this

#

You can fix it by adding an else and re-raising the error

junior verge
#

Uh sorry I don't know how to do that

sick birch
#
if isinstance(...):
  ...
elif isinstance(...):
  ...
elif isintance(...):
  ...
# so far your code looks like this, this is the part you need to add
else:
  raise error
junior verge
#

ahhh

maiden fable
#

imagine if raise error also called on_command_error lmao
Recursion ftw!

sick birch
#

stack overflow error go brr

#

recursion problems are the hardest to solve and the hardest to get my head around

#

for that very reason i hate binary trees

maiden fable
#

Haha

pliant gulch
#

Throwback to when nova made a recursive @property

maiden fable
#

huh how?

pliant gulch
#

Idk but he did it

maiden fable
#

lmao how tf do u make a recursive property

#

which repo was it in?

pliant gulch
#

I don’t know

maiden fable
#

Oof rip

flat solstice
#

random not really python question: I have a file for my bot sub class, I was calling it bot_subclass but that's a bit lengthy, anyone have any idea for what i should name it. I want to avoid just calling it bot since my bot var is called bot and it might get some import issues (I import my bot var from my main file in some cogs, mainly for dynamic choices based off of info in my bot var)

sick birch
slate swan
#

because the file doesnt exist 😔

#

nice

junior verge
#

I am drunk rn how to delete bots message lmao

maiden fable
#

msg = await ctx.send(...)
await msg,delete()

junior verge
#

ty xd

slate swan
maiden fable
#

@junior verge there is delete_after too

#

Well 🤷

slate swan
#

only if you want a timed deletion though

maiden fable
#

yea

slate swan
#

and why's your nick like that, it looks so weird lmao

maiden fable
#

cz Ellipsis has been saving my life 👀

slate swan
#

I'll better be off from here

junior verge
#

!paste

hybrid mural
#

under since it blocks everything that comes after it

#

so basically make it the last command you run in main

#

So how do i get the cooldowns from commands.cooldown and how do i make an error handling(if user is on cooldown and tries to use the command again)

slate swan
#

how can I use slash commands in a cog? is something wrong?

hushed galleon
dull terrace
#

i'm gonna flip. i can't get discord-py-interactions working on my aws.

#

it just tells me it's not there

hybrid mural
dull terrace
#

even though it's literally right there in the folder with every other package

#

it wont let me uninstall it with pip

hushed galleon
dull terrace
#

only that package has a problem

gaunt ice
#

<@userid> this is a mention

hushed galleon
hybrid mural
#

you could do async def hey (ctx, whatever)
if whatever == discord.Member i think

#

something along that

dull terrace
stable spire
#

ok

hushed galleon
hybrid mural
#

try printing the id to see if it works (should be some random number like 2142152142131)

dull terrace
#

okay i thought i deleted everything but it seems to think the requirement is already satisfied but only for that package eye_think

scarlet aurora
#

how can i make asyncio create a thread?

hushed galleon
hushed galleon
unkempt canyonBOT
#

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

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

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

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

okay i've only got the distribution info in my package folder for some reason, searching pc for discord-py-interactions thinking_vibrate

slate swan
#
    @commands.command()
    async def mute(self, ctx, member:discord.User=None, *, reason="No reason"):
        if member is None:
            embed=discord.Embed(description=f"**Please mention a member you want to mute. `{prefix}mute <@member> [reason]`**", color=0x6fccd4)
            await ctx.send(embed=embed)
        else:
            mutedrole = discord.utils.get(ctx.guild.roles, name="muted")
            if mutedrole:
                try:
                    member.add_role(mutedrole)
                    embed = discord.Embed(description=f"**{member.name}#{member.discriminator}** is muted sucessfully.", color=0x6fccd4)
                    await ctx.send(embed=embed)
                    try:
                        embed = discord.Embed(description=f"**you have been muted in {ctx.guild} for `{reason}`**",color=0x6fccd4)
                        await member.send(embed=embed)
                    except:
                        pass
                except:
                    embed = discord.Embed(description=f"**Some error has occurred**", color=0xff0000)
                    await ctx.send(embed=embed)
            else:
                embed = discord.Embed(description=f"**please create a role named `muted`, and set it's perms**", color=0xff0000)
                await ctx.send(embed=embed)

whats wrong here? i keep getting the error embed

dull terrace
#

okay so only the distribution info folder exists for discord_py_interactions... yet requirements are satisfied for pip

slate swan
dull terrace
#

i forced pip to install to the right folder and

#

still doesnt find the module

slate swan
#
    @commands.command()
    async def mute(self, ctx, member:discord.User=None, *, reason="No reason"):
        if member is None:
            embed=discord.Embed(description=f"**Please mention a member you want to mute. `{prefix}mute <@member> [reason]`**", color=0x6fccd4)
            await ctx.send(embed=embed)
        else:
            mutedrole = discord.utils.get(ctx.guild.roles, name="muted")
            if mutedrole:
                try:
                    await self.client.add_roles(member, mutedrole)
                    embed = discord.Embed(description=f"**{member.name}#{member.discriminator}** is muted sucessfully.", color=0x6fccd4)
                    await ctx.send(embed=embed)
                    try:
                        embed = discord.Embed(description=f"**you have been muted in {ctx.guild} for `{reason}`**",color=0x6fccd4)
                        await member.send(embed=embed)
                    except:
                        pass
                except:
                    embed = discord.Embed(description=f"**Some error has occurred**", color=0xff0000)
                    await ctx.send(embed=embed)
            else:
                embed = discord.Embed(description=f"**please create a role named `muted`, and set it's perms**", color=0xff0000)
                await ctx.send(embed=embed)

why am i keep getting this embed? everything should be fine

pliant gulch
#

Whichever you use to decorate callbacks to turn them into slash commands

high nexus
#

Yo how can I check if a member exists in a guild

stuck oyster
#
# == Variable interval ==
guild_id = 952497213945311262#guild id
status_keyword = ''#The status keyword
role_id = 959519173522890772#The role id
# =======================

@tasks.loop(seconds = 2)
async def statusCheck():
    guild = client.get_guild(guild_id)
    role = guild.get_role(role_id)

    for member in guild.members:
        if status_keyword in str(member.activity) and not role in member.roles:
            try: await member.add_roles(role)
            except: print(f'Try to give {member.name} role, but fail')
        elif status_keyword not in str(member.activity) and role in member.roles:
            try: await member.remove_roles(role)
            except: print(f'Try to give {member.name} role, but fail')


@statusCheck.before_loop
async def doesnt_matter():
  await client.wait_until_ready()```

The bot isn't giving the role why ( i removed the status keyword so they won't delete my message)
hushed galleon
#

Client.add_roles() is extremely outdated too

stuck oyster
hushed galleon
hushed galleon
#

did you try using print statements to see if the loop runs at all

hushed galleon
#

also a more efficient implementation would be to listen for the on_member_update event and check if their activity changes there, alongside a start up task similar to what you have now to handle updating roles when turning on your bot

hushed galleon
#

can you show your bot constructor with intents and also the lines where you start the loop and the bot (minus token if visible)

stuck oyster
# hushed galleon can you show your bot constructor with intents and also the lines where you star...
import disnake as discord
import os
import asyncio
from disnake.ext import commands, tasks


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

client = commands.Bot(command_prefix='-', intents=intents)
client.remove_command("help")


# == Variable interval ==
guild_id = 952497213945311262#guild id
status_keyword = ''#The status keyword
role_id = 959519173522890772#The role id
# =======================

@tasks.loop(seconds = 2)
async def statusCheck():
    guild = client.get_guild(guild_id)
    role = guild.get_role(role_id)

    for member in guild.members:
        if status_keyword in str(member.activity) and not role in member.roles:
            try:
                await member.add_roles(role)
                print('Hi')
            except: 
                print(f'Try to give {member.name} role, but fail')

        elif status_keyword not in str(member.activity) and role in member.roles:

            try: 
                await member.remove_roles(role)
            except: 
                print(f'Try to give {member.name} role, but fail')


@statusCheck.before_loop
async def doesnt_matter():
  await client.wait_until_ready()


@client.event
async def on_ready():
  await client.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name=f""))
  statusCheck.start() 
  print(f"Logged in as {client.user}")```
hushed galleon
#

you're missing the presences intent still

#

also did you run your client at all?

stuck oyster
#

?

#

yes

hushed galleon
#

intents.presences = True is needed for your bot to read activities, otherwise every user will just show as offline (iirc)

maiden fable
#

yes

stuck oyster
#

alright

vale wing
hushed galleon
#

also .start() should and does not need to be called in on_ready

stuck oyster
#

alright

vale wing
hushed galleon
#

just call it before running the bot

#

it already has a before loop to wait until ready

vale wing
#

Won't it cause issues with asyncio

hushed galleon
#

actually maybe with dpy 2.0

maiden fable
vale wing
#

I always do them in cogs so idrk

#

Basically it's called on cog instance creation

maiden fable
#

Understandable

#

Same

vale wing
#

So before running as well

pliant gulch
#

You don't need to call task.start() inside of on_ready if anything that would cause problems

vale wing
#

Not sure how does loop mechanism work in dpy

pliant gulch
#

It's a glorified while True basically

hushed galleon
#

well i say would but i currently cant test it to double check

vale wing
#

bot.run basically launches asyncio application so how can it run other async functions before

#

Another event loop or something

hushed galleon
#

it just submits a task to the current event loop, and in 1.7 it also automatically creates an event loop when one doesnt exist

vale wing
#

Mk

hushed galleon
#

i think constructing the client also used to create an event loop too

#

certain characters like whitespace are disallowed from being used in text channel names

#

the most robust solution is keeping track of their ticket channel's id in a database

pliant gulch
hushed galleon
#

in 2.0 afaik thats only done in bot.run()

dull terrace
#

what's the best package for slash commands and components

pliant gulch
#

Which is called by run -> start -> login -> _async_setup_hook

hushed galleon
#

that internal method uses get_running_loop, which doesnt actually create the loop

#

asyncio.run in client.run is what creates it

pliant gulch
#

But that's just how I did things before

hushed galleon
#

yeah, there's a plethora of changes they've made

pliant gulch
#

Weird how discord.py decides to care about the get_event_loop deprecation, yet still use old ass stuff

hushed galleon
#

query your database when they click your button to check for their corresponding ticket

#

if an entry exists for them, you could also double check that their ticket channel is still there in case an admin deleted it

dull terrace
#

disnake the best option?

hushed galleon
#

i know the @unkempt canyon bot finished migrating to disnake last month, like 30 minutes before discord.py's un-archival was announced

pliant gulch
#

Lmao amazing timing

#

But the core devs had a good reason

dull terrace
#

well i just found out that they dropped support to discord_slash in their server

hushed galleon
pliant gulch
#

Disnake is being actively developed, therefor unstable

dull terrace
#

so done with them

pliant gulch
dull terrace
#

alright but then which package is stable suspicious

pliant gulch
#

If you want v2.0 things, just fork, and download through your fork's github repo

#

So, you basically "freeze" it

#

That way it isn't so unstable

hushed galleon
#

your package manager should already have an option to freeze to a specific commit

#

pip freeze command or the poetry.lock file

pliant gulch
#

So when things break, they break bad/hard

dull terrace
#

alright so basically just use disnake

hushed galleon
#

wonder how many times dpy master had critical bugs introduced

#

that being said they are using unit testing for the app commands and a few other modules

pliant gulch
#

Crazy, codecoverage must be 50% now?

#

Kek

hushed galleon
#

yea definitely not a lot

dull terrace
pliant gulch
#
import cursecord

async def main() -> None:
    guild = cursecord.Guild.precreate(id=...)

    async with cursecordCursedClient(....) as (client, gateway, rest):

        @gateway.on(cursecord.MESSAGE_CREATE)
        async def message(message: cursecord.Message) -> Iterator[str]:
            yield f"I got a message from {message.author}"

        @guild.on(cursecord.GUILD_DELETE)
        async def deleted(guild: cursecord.Guild) -> None:
            print("deleted")

     await gateway.setup()

asyncio.run(main())
``` some cursed idea's for my late april fools joke wrapper
dull terrace
#

oh i see the context menus

pliant gulch
#

what part

maiden fable
pliant gulch
#

We do a little trolling

maiden fable
#

Haha

vale sierra
#

intents

stone beacon
#

Probs cuz the name of ur function and variable are in fact the same

#

If that's pycharm ur using then that's most likely why

#

Rmr opening a repo on that and got 200 pep errors

vale sierra
maiden fable
#

Bro

dull sorrel
#

How do I strip all punctuations from a message and then match it?

vale sierra
#
   @bot.command()
    async def embed(self, ctx, title, *, description):
        embed = discord.Embed(title=title, description=description, color=0x1630C3)
        await ctx.send(embed=embed)
``` try something like this and make every change you want
final iron
#

<@&831776746206265384>

#

It's just... disturbing

vale sierra
#

intents it

wicked atlas
#

It's probaby because embed is already the name of the function

blissful lagoon
#

@vale sierra lets not post things like that please

wicked atlas
#

?

dull terrace
#

how long do you think until discord.py 2.0 is working well suspicious

vale sierra
#

i have it in my code its not this

wicked atlas
#

That warning is just pycharm telling you that you are reusing a name

#

Shouldn't affect your code running though

vale sierra
#

@proven shale

#

try running this code with your discord bot

wicked atlas
#

I think they ment indent

#

not sure though

vale sierra
#

yes sorry indent haha

wicked atlas
#

there wasn't anything wrong with indentation there

vale sierra
#

the indent is wrong here

wicked atlas
#

on what line?

vale sierra
wicked atlas
#

In your case, embed is the name from the outer scope

#

I would suggest using a different variable name for that embed

#

or even just putting it directly in the send

vale sierra
#

but its dont affect the code i think bc i have the same in my code

wicked atlas
#

Your function name?

#

Well now your command is <prefix>embed_func

#

If you want to do it that way, you can name the function by using

@bot.command(name="embed")
#

What exactly did you try here?

#

That's not exactly how you send commands

#

Did you run your command with <your-prefix-here>embed_func?

#

But that command is not help

#

it is embed_func

#

No, it would just output embed_func as a literal string

#

Do you know how the command system works?

glacial echo
#

can i do a thing where if someone sends a command, i activate a different "function" only when the corresponding value is passed through the comand?

sick birch
#

Well yes because copy pasting won't get you anywhere, and all the videos code are outdated and suck

glacial echo
#

i was thinking using await wait_for() but can i make those also check a channel?

sick birch
#

Don't change presence in on_ready, and you need to process_commands if you're using an on_message event.

pure sparrow
#

hey guys, if anyone is interested to host a bot 24/7 in python totally free I have a youtube video that was really helpful for me. my bot is now hosted without paying anything. of course you can pay to upgrade it but that's not important

opal gyro
#

who has invite link for discord.js serv3r

sick birch
#

You can just call a function if an argument is equal to something

pallid mango
#
        logs = commands.get_channel()
        general = commands.get_channel()

i have this as my code in a cog, once it gets to this part it wont send and says, no attribute get_channel

opal gyro
#

who has invite link for discord.js serv3r

sick birch
opal gyro
wicked atlas
#

If yo have an on_message event, then commands won't work

sick birch
latent ember
#

I need help making a mute command

iron sorrel
#

guys how do i subclass the Client?

latent ember
#

cand someone teach me

pallid mango
#

class Commands(commands.Cog):
"""Moderation commands!"""
def init(self, bot):
self.bot = bot

#

def setup(bot):
bot.add_cog(Commands(bot))

iron sorrel
#

!cod

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

sick birch
#

I'm talking about lowercase c, commands

wicked atlas
pallid mango
sick birch
wicked atlas
pallid mango
pallid mango
sick birch
glacial echo
sick birch
glacial echo
#

yes

sick birch
#

Or just invoke a command with an argument?

pallid mango
sick birch
#

Ah, I see. Then yes, wait_for is your best bet

glacial echo
#

someone invokes /start_game and then we wait for the relevant player to send a message

sick birch
sick birch
glacial echo
#

since if a player doesnt respond within the time limit they get removed from the player list

wicked atlas
#

you could honestly just remove the on_message function altogether

glacial echo
#

but how can i make it pick which wiat_for() section to use

sick birch
#

process_commands() takes a message instance

sick birch
pallid mango
#
client = commands.Bot(
  command_prefix = ".", 
  case_insensitive = True,
  intents = discord.Intents.all())```

you mean this?
sick birch
pallid mango
#

yea i know but im not understanding what you mean by "what the variable is"

#

i get which word youre talking about, just not what youre asking

sick birch
#

What are you assigning to it basically

pallid mango
#

ohhhhh

#
        logs = commands.get_channel(958932470710030431)
        general = commands.get_channel(919024467353677883)
        await logs.send(f"{user} has been permanently global banned by {ctx.author.mention} for {reason}!")```
#

this?

sick birch
#

No, it should look like

commands = # what's here?
pallid mango
#

oh, one second

dull terrace
#

contemplating whether to migrate to disnake or wait a couple weeks and hope that a stable version of discord.py comes out ablobsweats

pallid mango
#

i don't have any code like that

dull terrace
#

both seem like terrible options

glacial echo
#

based on the int value of the argument it takes

#

mmm i have an idea that might make my current line of questioning irrelevane

pallid mango
glacial echo
#

wait

#

hmmm ive kidna fucked myself here cause i dont wanna gore my code but i think i have to slice up large swaths of it

wicked atlas
#

👍

dull terrace
#

alright disnake it is

slate swan
#

plus disnakes implementation is pretty good unlike dpy which main has allot of asyncio breaking changes

#

Is it possible to make the bot ignore the channel in on_message?

slate swan
#

!d discord.Message.channel

unkempt canyonBOT
slate swan
#

okay

#

it returns a TextChannel ofc if it is one which TextChannel has an id attr

unkempt canyonBOT
pliant gulch
#

😔 Cannot fishhook int.created_at since typehints don't work

glacial echo
#

hwo do i format check

#

and what can it actually check for

slate swan
pliant gulch
#

Check would be a callable that takes the same parameters as the event, then you return a bool

#

If the callable returns True it will capture that, otherwise ignore

glacial echo
#

hmm

#

so like if i want to check if the author is a vertain variable?

latent ember
#

how to make an mute command?

slate swan
glacial echo
#
message = await client.wait_for("message", check=)
glacial echo
slate swan
glacial echo
#

hmm

#

still drawing a blank for any of the words meanign anyhting

#

unfortunately

slate swan
pliant gulch
latent ember
#

im tired

slate swan
slate swan
latent ember
slate swan
#

library

#

which library are you using

latent ember
#

Umm im not sure

slate swan
#

bro

latent ember
#

yes

slate swan
#

which version?

sly hamlet
#

That sends a second message? And doesn't edit the current one

slate swan
#

what

latent ember
#

wait

#

the current one?

slate swan
sly hamlet
#

like sending a embed then a message with interactions

slate swan
#

pardon?

latent ember
#

im tired idk

slate swan
#

you mean sending a followup message?

latent ember
#

the newest one

slate swan
latent ember
#

that you can download

slate swan
#

stable or master?

sly hamlet
#

Like you send one message that's an embed and then directly after that you sent another message and that's a regular text message

glacial echo
#

i feel like my brain just developed a lot of new neuron connections

#

thank you for making me have ot comprehend lambdas

latent ember
#

this one?

slate swan
#

thats master yes

slate swan
#

or andy?

latent ember
slate swan
glacial echo
#

i have the followign garbage no good code that definitely wont work, how can i make it so this loops that check for a message in teh wait_for() once a game has started up until a game has ended

glacial echo
#

am i gonna be writing my own coroutine or some shit

#

since on message wont work

latent ember
slate swan
#

and you cant use is

glacial echo
#

why ant i use is

sly hamlet
glacial echo
#

does is not return a bool?

latent ember
glacial echo
latent ember
#

nothing just tired and dont really wanna do extra work rn

glacial echo
#

thats outdated a olot

latent ember
#

wanna just add an mute command.

slate swan
slate swan
glacial echo
#

ah

glacial echo
#

shoudlnt they be the same

slate swan
#

its used to compare objects

hushed galleon
#

the is operator checks object identity, i.e. is a the same object in memory as b, which usually isnt what you want since you need to be extra sure you're expecting the same object - even with integers, it is still possible for python to construct two different integer objects with the same value

glacial echo
slate swan
glacial echo
#

alright well i can use == thats not a problem

hushed galleon
#

for most purposes the appropriate operator is == which checks equality, i.e. disconnected from memory location

slate swan
#

!d is

unkempt canyonBOT
#
is

6.10.3. Identity comparisons

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. 4

final iron
glacial echo
#

ok so back to the more pressing issue

#

i need it to always be waiting for that message

slate swan
#

which message

glacial echo
#

the message im waiting for in wait_for(...)

slate swan
#

what about the method

glacial echo
#

i need this to be always active, or active whenever a game is being played

#

not only on a one of event occuring

#

and on_message foesnt work becasue i cant seem to implement a timer in it

#

well, not effectively

slate swan
#

!e

print(False is 0)
print(False == 0)

@glacial echo example on is

unkempt canyonBOT
#

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

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
003 | True
slate swan
#

first print statement returns False as theyre not the same object but the second one returns True as 0s bool is False

#

!e

print(bool(0))
unkempt canyonBOT
#

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

False
hushed galleon
slate swan
#

is compares objs while == compares values

glacial echo
#

not at all

#

someone runs a command of syntax /start_game [int] where int determines the game to eb played

#

then once a game ahs started all players in the channel (the members of the list) should be able to play on their turn

#

this is achieved with checking the first position in the list and then popping it after their turn

#

i need to always check for a message being sent in the active game channels

#

but im using wait_for and not on_message because wait_for has a built in timeout

slate swan
#

just check a list of the member ids and use an iterator ig

glacial echo
hushed galleon
#

when did wait_for have a built in timeout?

slate swan
glacial echo
maiden fable
slate swan
#

its pretty helpful

glacial echo
#
    isPlayer = lambda message : message.author.id == client.players[message.channel.id][0]
    message = await client.wait_for("message", check = isPlayer, timeout = 150)
slate swan
#

no

#

dont use wait_for

#

just use on_message

hushed galleon
#

yeah the docs straight up says by default it doesnt time out

glacial echo
#

i can time out wait_for

#

by setting teh timeout to a number

hushed galleon
#

does your game have to last a very long time? i.e. more than an hour or across bot restarts?

glacial echo
#

no it has to kick the player out of the list after 2 adn a half minutes

hushed galleon
#

oh i misinterpreted your last message

abstract kindle
#

How would you do it?

worldly solstice
#

Hey there! Any hints where i can host my bots online 24/7?

sick birch
abstract kindle
#

You miss the point

#

The question was how to avoid the built in cooldowns resetting every time I reloaded the cog or the bot was rerun for some reason

sick birch
abstract kindle
#

Would the way I suggested work as a temporary workaround?

sick birch
#

I think that's the only way

abstract kindle
#

The cooldowns are only going to be happening once per day anyway...

#

So it's not like it would be extremely inefficient

sick birch
#

Oh if it's only once per day then yes for sure

abstract kindle
#

Okay, cool

hushed galleon
sick birch
#

When the user runs a command, fetch and check if the timedelta is over a day, is that what you're saying?

abstract kindle
#

Yep, except I'm just using timestamps and seeing if the difference is greater than 86400

sick birch
#

You know, discord.ext.tasks abstracts away that worry from you:

worldly solstice
abstract kindle
sick birch
sick birch
abstract kindle
#

Maybe, but I think just writing the times to the user in the db would work too

#

Another question if you don't mind

glacial echo
#

or do awaits work outside of an async

slate swan
#

thats not how coroutines work

sick birch
slate swan
#

!e

async def a():
    ...
await a()
unkempt canyonBOT
#

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

001 |   File "<string>", line 3
002 | SyntaxError: 'await' outside function
sick birch
abstract kindle
#

Also, if I want to self host, but I edit my code from another computer, how would I accomplish editing / uploading. For example, I code on my laptop, but that doesn't stay on 24/7. I want to host it on my PC.
Is there some application I would use to do something like this?

sick birch
#

Yeah, you'd wanna set up github CI/CD

slate swan
sick birch
#

So pushing to github automatically validates it, and deploys it to your production server

slate swan
#

arent coros in js called promises?

sick birch
#

Yessir

slate swan
glacial echo
#

man at this point i have to do a proper rewrite of this bot

hushed galleon
slim ibex
#

JavaScript async 😔

sick birch
#

Though it's kind of opposite it feels like. JS is normally async (at least it feels like it) so awaiting is like making it synchronoized

glacial echo
#

which is to be expected but sadge

sick birch
#
const res = fetch(...);
return res;

returns undefined because it returns before fetching

glacial echo
#

easiest way to check for a list being empty?

sick birch
#

!e

x = []
if x:
  print("List is not empty")
else:
  print("List is empty")
unkempt canyonBOT
#

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

List is empty
sick birch
glacial echo
#

oh cool

slate swan
#

0, "", [], () all return falsey

slim ibex
#

await better 🗿

abstract kindle
#

whats falsy?

slim ibex
#

promise chaining in JS fucks me over

slate swan
slim ibex
slate swan
#

how do you thread an async function? cant find really something on the net

sick birch
#
fetch(...)
  .then(() => {
    return ...;
  });

but typescript doesn't like that so await is better

abstract kindle
#

oh lol

sick birch
#

Something that is false-like, empty strings, 0, empty tuples, etc

slate swan
unkempt canyonBOT
#

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

001 | False
002 | False
abstract kindle
#

Ohhh, so not exactly False, but false in nature

slim ibex
#

Well a better way to put it would be something that evaluates to false

abstract kindle
#

Lol

#

Mixed signals

slate swan
#

False value but not the False obj

abstract kindle
#

That's what I said basically

sick birch
#

Semantics of speech

slate swan
#

i.e is is used for checking entities

abstract kindle
#

I got the idea, thanks

slate swan
#

!e

print(False is 0)
print(False == 0)
unkempt canyonBOT
#

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

001 | <string>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
002 | False
003 | True
slim ibex
#

Going off what I said for it being False, it was interpreted as foo = False. The right way to say it is that the object is falsy because it is empty: foo = []

#

[] itself isn’t a Boolean

slate swan
#

but has a bool value

slim ibex
#

^

abstract kindle
#

does everything have a bool value?

slate swan
#

like cheese its cheese but its made out of milk and its yummy

slate swan
abstract kindle
#

cool

hybrid mural
#

Is there a way to start tasks.loops not in setup ?

sick birch
# worldly solstice Awesome, ty! Is it hard to set up? Not really experienced with this stuff. What ...

I also meant to mention. I'm running a small scale bot and dashboard, so I run my bot, a postgresql database, an API middleman for the bot and database, and the dashboard in itself. Also a domain from Route 53 and S3 as well, but that's beside the point. Not very scalable, but I plan to migrate them all to their own instances and set up a load balancer in front, and move the database to AWS RDBMS.

slate swan
unkempt canyonBOT
#

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

001 | False
002 | True
003 | False
004 | True
sly hamlet
#
Ignoring exception in command 'play2':
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 457, in _invoke_with_namespace
    return await self._callback(self.binding, interaction, **values)  # type: ignore
  File "C:\Users\culan\OneDrive\Desktop\echo slash\cogs\testmusic.py", line 524, in play2
    await interaction.response.send_message(embed=[song])
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 595, in send_message
    params = interaction_message_response_params(
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 485, in interaction_message_response_params
    data['embeds'] = [embed.to_dict()]
AttributeError: 'list' object has no attribute 'to_dict'

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

Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 998, in call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 476, in _invoke_with_namespace
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'play2' raised an exception: AttributeError: 'list' object has no attribute 'to_dict'

``` any thoughts on this I'm unaware of how to fix it
slim ibex
#

oops

slim ibex
#

!e print(False != (False or (True and False)) and True)

unkempt canyonBOT
#

@slim ibex :white_check_mark: Your eval job has completed with return code 0.

False
sly hamlet
abstract kindle
#

What.

slate swan
sly hamlet
#

You said in bed was a list doesn't exactly tell me what I did wrong

slate swan
#

bro

abstract kindle
#

you tried to use an attribute that doesn't belong to lists

hushed galleon
#

you did exactly what okimii stated - by putting [] square brackets around the song variable, you've enclosed it in a list object

slate swan
#

embed is literal to a list object

abstract kindle
#

["im in a list"]

slate swan
#

thats how python works variables are literal to there values and functions are literal to there return type

slim ibex
#

just remove the brackets

sly hamlet
#

So get rid of the brackets? Because it's only one embed?

abstract kindle
#

"im not in a list"

slate swan
hushed galleon
sly hamlet
#
await interaction.response.send_message(embed = song)``` so this?
slate swan
# slate swan what

data['embeds'] = [embed.to_dict()] AttributeError: 'list' object has no attribute 'to_dict'
is hes error stating embed is a list but yes the return type of to_dict is a dict so hes just closing a dict inside of a list

hushed galleon
#

embeds=[song] is probably what you intended if you wanted to pass your song embed in a list

abstract kindle
#

^ that's the error....

slim ibex
abstract kindle
#
AttributeError: 'list' object has no attribute 'to_dict'```
hushed galleon
#

ok you either write embed=song, or embeds=[song]

abstract kindle
#

curious, what does it mean when it says Ignoring Exception in commmand?

sly hamlet
#

The one with the brackets is the one that's giving me the problem and the one that I just had in

slate swan
slim ibex
abstract kindle
#

Why is it ignoring it?

slate swan