#discord-bots

1 messages Β· Page 45 of 1

junior verge
#

yeah thats what I am doing now

#

just made a temp command for that

slate swift
#

can you help me with a error

hushed galleon
#

Event loop is closed isnt an error you have to worry about

#

its just a bug with the ProactorEventLoop that windows uses

slate swift
hushed galleon
#

is there a different error in your terminal when you scroll it up?

glad cradle
# slate swift

there's your token, reset it on discord developer site

hushed galleon
#

and enable all the privileged intents within that same bot page

slate swift
#

works now

junior verge
#
@client.command()
@commands.has_permissions(manage_messages=True)
async def temp(ctx, level):
    async with client.db.cursor() as cursor:
        await cursor.execute("DELETE FROM levelSettings WHERE guild = ? and levelSettings = ?", (ctx.guild.id, level,))
        await client.db.commit()
    await ctx.send("Removed the level")
``` just trying to make a temp command so I can do ``.temp 1` (1 would be the level whereyou would get x role what says None) and it would remove that but this is not working either
hushed galleon
#

well what did you name the third column that stores the role's level?

slate swift
#
from discord.ext import commands

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

@bot.event
async def on_ready():
    print("Bot is online")


@bot.event()
async def ping(ctx):
    await ctx.send("pong")```
#

do i change to client.event

spice carbon
#

how can i make a reminder command without using sleep? sounds too lazy just sleep for a time

junior verge
# hushed galleon well what did you name the third column that stores the role's level?

uh not too sure tbf this was the insert command

@client.command(aliases=["sr", "addrole"])
@commands.has_permissions(manage_messages=True)
async def setrole(ctx, level: int, *, role: discord.Role):
    async with client.db.cursor() as cursor:
        await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,))
        roleTF = await cursor.fetchone()
        if roleTF:
            return await ctx.send("A role or level setting for that value already exists")
        await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, role.id, level, ctx.guild.id,))
        await client.db.commit()
    await ctx.send("Updated that level role")
hushed galleon
#

so just do the same thing for your second event

slate swift
hushed galleon
#

its like calling an integer, 1(), some things just dont let you do that

hushed galleon
junior verge
slate swift
#
from discord.ext import commands

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

@bot.event
async def on_ready():
    print("Bot is online")


@bot.event1()
async def ping(ctx):
    await ctx.send("pong")
slate swift
glad cradle
#

and ping is not an event

#

it's a command

slate swift
glad cradle
#

it should be @bot.command()

glad cradle
slate swift
#

oh yea bot.command

#

i forgot

glad cradle
spice carbon
# silk fulcrum scheduling

I store the date in a database and check like every 10 sec if the current date it's equal to the stored one? doesnt sounds correct, since one second of difference would make the times distinct... not sure how to implement that without checking literally every sec

slate swift
limber bison
#

where i can read about string[1:-1]

#

this ?

silk fulcrum
#

!slices

#

:(

#

!slicing

#

:((

glad cradle
#

btw the roles list doesn't make sense

#

yes

#

you already have interaction.author.roles

#

it's already a list

prisma prism
#

Hi could someone help me out with some sample code?
I want to add a reaction to an already sent message but my code doesn't work.

glad cradle
#

interaction.user.roles return a list of roles

#

you're iterating the list to create another list

#

this doesn't make sense coz there's no if statement

#

you're practically copying the list

#

yes but it's useless, try to print roles and interaction.user.roles and compare the items

#

ok

#

btw what's the problem

#

is it a error?

#

uh, I think there's a problem with the sql query

#

transactionId query is returning None

#

idk your database, also where should be capitalized WHERE from too FROM

#

int was not the problem

#

the problem here is that the sql query is returning None

#

you need to work on the sql query

limber bison
#

3^2 = 9 how can i do in python >

#

10^x

#

i want this

glad cradle
unkempt canyonBOT
#

@glad cradle :white_check_mark: Your 3.11 eval job has completed with return code 0.

9
slate swan
#

can some one show me how to make a bot

leaden cosmos
#

go and watch the newest
all system are on yt

slate swan
#

none of them worked for me

#

it has the token in it

leaden cosmos
unkempt canyonBOT
#

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

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

slate swan
#

hmm

leaden cosmos
#

ok bye

unkempt canyonBOT
#

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

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

slate swan
#

the token

#

alr

unkempt canyonBOT
#

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

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

slate swan
#

can some one show me on how to make a bot

slate swan
#

how can i read messages someone has sent to my bot

slate swift
#
async def embed(ctx, member:discord.Member = None):
    if member == None:
        member = ctx.author

    name = member.display_name
    pfp = member.display_avatar

    embed = discord.Embed(title="This is my embed", description="Its a very cool embed", colour=discord.Colour.random())
    embed.set_author(name=f"{name}", url="", icon_url="")
    embed.set_thumbnail(url=f"{pfp}")
    embed.add_field(name="This is 1 feild", value="This field is just a value")
    embed.add_field(name="This is 2 feild", value="This field is inline True", inline=True)
    embed.add_field(name="This is 3 feild", value="This field is inline False", inline=False)
    embed.add_footer(text=f"{name} Made this Embed")
    
    await ctx.send(embed=embed)```
#

can someone help me fix this error?

quaint epoch
unkempt canyonBOT
#

property guild_avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the guild avatar the member has. If unavailable, `None` is returned.

New in version 2.0.
quaint epoch
#

!d discord.Member.default_avatar

unkempt canyonBOT
#

property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.default_avatar "discord.User.default_avatar")
quaint epoch
#

!d discord.Member.avatar any of these work

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
leaden cosmos
#

also member.name is enough (real name)
member.display_name is name in server

glad cradle
#

he could do pfp = member.avatar if member.avatar else member.default_avatar

#

member.avatar could be None

potent spear
#

pfp = member.avatar or member.default_avatar

knotty agate
#

does anyone know whats going on

im getting this error when i try to run my discord bot on replit

Traceback (most recent call last):
  File "main.py", line 133, in <module>
    client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'

but i have never had this error befor and on my computer it runs fine

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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

sick birch
#

The reason it works on your computer is because you’re running an old version

knotty agate
#

oh ok

#

well the only events i use are on_message and on_ready

#

lol ive tried reading the docs but my bot still isnt working

#

i just dont know the names of the intents i want

sick birch
knotty agate
#

i have but im getting this error from when i try to start my loop

File "main.py", line 1199, in <module>
    event_manager.start()
  File "/home/runner/minecraft-bot/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 398, in start
Press CTRL+C to quit
    self._task = asyncio.create_task(self._loop(*args, **kwargs))
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/tasks.py", line 381, in create_task
    loop = events.get_running_loop()
RuntimeError: no running event loop
sick birch
#

How are you starting the event loop

knotty agate
#

also for context event_manager is just this

@tasks.loop(seconds=60)
async def event_manager():
  #code
knotty agate
sick birch
#

What is event_manager

#

Your bot?

knotty agate
#

It is a loop in my bot

#

That loops every 60s to edit certian messages

eager hill
#

my goal is to say the word count and itll start listening for a number than add 1 to it

#

can anyone explain or redirect me to a tutorial

wanton pebble
#

am I allowed to/is it possible to launch 2 bots at once in the same code?

sick birch
wanton pebble
wanton pebble
sick birch
#

πŸ€” not sure how having multiple bots on the same file is going to help with that

wanton pebble
sick birch
knotty agate
#
intents = discord.Intents.default()
intents.messages = True
client = discord.Client(intents=intents)

Ive also taken the neccicary action on the developer portal

My bot is able to come online, but its not responding to any commands :(

Does anyone know what im doing wrong

wanton pebble
sick birch
knotty agate
#

Ah

#

Thanks alot :)

sick birch
dry kelp
#

@sick birch

#

Do u have any idea why this won't work?

primal token
sick birch
dry kelp
#

before and after overwrites. Should be channel permissions

wanton pebble
dry kelp
#

Nope. It won't print also

#

on_guild_channel_update

#

It just won't print once a change is being made to the channel permission lol

sick birch
#

Does the event even get called?

dry kelp
#

it should get fired yes

#

if u want i can run a test but it 100% works

sick birch
#

Can you post the entire function not just a snippet

#

Oh you just did that

dry kelp
#

haha yes πŸ˜‚

knotty agate
#

Ahahaha yay yet another error :)

Now its saying discord.Member has no attribute avatar_url_as

Is this another intention?

dry kelp
#

i was just working on other stuff when i noticed in the models of the antinuke that i forgot to add channel perms check.

dry kelp
#

And i just tried looking thru the docs and stuff but nope

#

it just won't print

#

the only parameter for permissions is overwrites

sick birch
#

Audit logs are really inconsistent so if there's not a code error there's not much you can do

dry kelp
#

Yeah i know it takes a few secs before it shows up in the audit

#

should i try to sleep the event? for a few seconds

#

then see what it does?

sick birch
dry kelp
#

It currently does. I can see that in the audit logs

sick birch
#

Okay, looks like you got lucky. I'd suggest put a print statement inside the for loop first to see if the for loop is being called

dry kelp
#

sure

knotty agate
# sick birch `avatar.url`

No that dosent work :(

Im using the avartar in pillow to put in a picture.

discord.Member.avatar_url_as works on my computer, i just need to know what they changed it to lol

sick birch
unkempt canyonBOT
#

class discord.Asset```
Represents a CDN asset on Discord.

str(x) Returns the URL of the CDN asset.

len(x) Returns the length of the CDN asset’s URL.

x == y Checks if the asset is equal to another asset.

x != y Checks if the asset is not equal to another asset.

hash(x) Returns the hash of the asset.
sick birch
knotty agate
dry kelp
#

what the fuck wait

#

oh wait

#

Okay so robin the issue is not how im calling the audit log

sick birch
dry kelp
#

i see if i make other changes like renaming the channel it will fire the after async print

#

so the issue its probably in that check for permissions

sick birch
#

That would make sense

dry kelp
#

Uhm i have no idea what to do honestly

knotty agate
dry kelp
#

wish there were a permissions parameter for channels like for roles lol

knotty agate
dry kelp
#

What should i do? do u have any ideas? because i honestly dont

sick birch
knotty agate
#
Pfp = message.author.avatar_url_as(size=256)
sick birch
#

!d discord.Asset.with_size

unkempt canyonBOT
#

with_size(size, /)```
Returns a new asset with the specified size.

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

there

knotty agate
#

Ah

#

Okay i will try that thx alot πŸ‘

dry kelp
#

robin? πŸ˜‚

sick birch
#

Actually

#

I think you can remove that if statement alltogether

#

Because you're already checking for an action in your audit log lookup

knotty agate
dry kelp
#

@sick birch Not really. You don't know the rest of the code haha

#

this is currently just for test purpose to see if it works

#

it has multiple if statements to check what's going on and what to do

#

that's the point

#

also i can run a test without the if statement to see if it would work

#

@sick birch It works hahaaaaaa

#

Yes but i need an if statement so uhm.

knotty agate
#

With this new intents thing basicly every discord.py turorial is outdated

dry kelp
#

@sick birch i wanna tell u something dumb. I added the if statement back and now it works

#

πŸ˜‚

sick birch
#

πŸ€”

sick birch
dry kelp
#

i like more pycord x)

knotty agate
pale turtle
#

I have a question but it's really no 100% bot related. I want to make a leveling system, and I set everything other than the rank part. I did every message sent is between 15-25xp, and saved it in a database, but now I don't know which calculation I should do with that xp to make a rank system. Anyone can help

sick birch
pale turtle
sick birch
dry kelp
#

Robin how could i check if any role is being added here?

sick birch
dry kelp
#

let me search it up

#

Robin u sure? because i don't see that in the docs

pale turtle
knotty agate
sick birch
sick birch
quaint epoch
dry kelp
#

Robin i will try haha, nothing to lose

#

yes but in the edit. what's the parameter for it lol

pale turtle
sick birch
pale turtle
#

Honestly nothing

drifting arrow
#

How do I limit an app command to specific channel, role or permission?

dry kelp
#

@sick birch if a channel invite gets deleted, can the bot create one with the same url?

#

or it can create one but with a different url

pale turtle
#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.

Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.

This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
sick birch
sick birch
drifting arrow
dry kelp
drifting arrow
sick birch
dry kelp
#

it gets showed in the audit logs even when deleted also when created

dry kelp
#

Yes but pretty sure that the bot can create one back? true?

drifting arrow
sick birch
dry kelp
#

awesome

#

What's the param for it? i don't see it in channel

#

also i think ur right about guild.default_role found something

drifting arrow
dry kelp
#

@sick birch this won't work sadly

sick birch
#

well the default role never changes it's just @everyone

dry kelp
#

yes but what im trying to do is to see if a role is being added/removed

sick birch
#

So compare before.guild.roles to after.guild.roles

#

if the length is different, a role was added/removed

dry kelp
#

You have a point but instead of checking the len of the list

#

wouldn't it be easier if i just make to functions

if not before.guild.default_role and after.guild.default_role:
and
if before.guild.default_role and not after.guild.default_role:

#

lol won't this be a time saver? and work the same

#

and if its being added then remove it and if its being removed then add it back lol

sick birch
#

this will always evaluate to false

#

guild.default_role is sort of like a constant, doesn't change and is always there

dry kelp
#

wait wait wait

#

is this happening on the channel update event lol?

sick birch
sick birch
#

I don't understand what you're getting at here

dry kelp
#

I don't either because the audit logs are making it more confusing

#

added / removed role to the channel perm thing

#

let me look up for the invite url thing. i will stop doing this for a bit

dry kelp
drifting arrow
#

woo \o/

#

im figuring stuffs out \o/

#

This way of doing stuff is way better than my way. πŸ˜„

sick birch
#

How is it different?

drifting arrow
#

Still technically the same thing as what I was doing.. but looks better.

#

so the slash command still appears in all channels, i dont think I can get rid of that. 😦 However.

def check_channel():
        def predicate(interaction: discord.Interaction):
            return interaction.channel.id == 932137392738021427
        return app_commands.check(predicate)
    
    @app_commands.command(name="truetest10", description="Testing the thing!")
    @check_channel()
    async def truetest(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Works here!")

    @truetest.error
    async def on_test_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
        await interaction.response.send_message("ERROR ERROR ERROR")
``` is way better than
```python
    
    @app_commands.command(name="truetest10", description="Testing the thing!")
    async def truetest(self, interaction: discord.Interaction):
        if interaction.channel.id in my_channel_list
          await interaction.response.send_message(f"Works here!")
        else:
           await interaction.response.send_message("ERROR ERROR ERROR")
sick birch
drifting arrow
#

oh

#

lemme check!

#

OMG U CAN!!

sick birch
#

Yeah it's quite extensive. You can restrict to certain members, channels, roles, etc

drifting arrow
#

I removed all my checks on my bot and just left the command, and despite syncing, reloading, and doing all sorts of shit, it doesnt work at all

sick birch
drifting arrow
#

So I tried limiting the command to just 1 channel, didnt touch the users. The command was still able to be used in all the channels

sick birch
#

Could you send the code please

drifting arrow
#

same as above except without the checks.

import discord
from discord import app_commands
from discord.ext import commands
import traceback
import json, aiohttp, validators


TEST_GUILD = discord.Object(794837147068792862)

class staffapps(commands.Cog):
    
    def __init__(self, client):
        print("[Cog] Notes has been initiated")
        self.client = client
    
    @app_commands.command(name="truetest12", description="Testing the thing!")
    async def truetest(self, interaction: discord.Interaction):
        await interaction.response.send_message(f"Works here!")
    

async def setup(client):
    await client.add_cog(staffapps(client))
``` and In the integrations on discord:
#

as I said. I removed the checks to see if the discord app could do the same thing

sick birch
#

Can you see the /truetest command anywhere but #admin-zone?

drifting arrow
#

maybe it's coz im bot owner? try creating a new role and setting it to not work for role

#

I viewed as a new role and.. It's gone!

#

so perhaps it had something to do with my role?

#

Requires more investigation, but I'm pretty sure we're onto something!

sick birch
drifting arrow
#

Well. I'll still put all my checks in places just in case something fails

tired notch
#

in discord py 2 how can i make a clickable link in an embed

#

liek the text will be something like More Iformation Here and then it iwll ead to a link with more information'

#

in the footer i mean

mossy warren
#

is there a way to check if the message author has a certain role?

sick birch
tired notch
#

i meant in the footer but it is ok i did it another way

mossy warren
sick birch
#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
sick birch
#

Don't think you can have it in the footer but give it a shot

drifting arrow
#

;D

#

I finally finished v1 of my bot \o/

#

Still not as ideal as I had hoped. But one day I'll figure out how to do dynamic questions where the user can specify unlimited questions

worthy mortar
#

hey guys
any recommendations for how to make this text more pretty / appealing?

slate swan
#

how do

#

i add more text thing

#

so like if i say hey the bot will say hello so how do i add more

worthy mortar
slate swan
#

i know

#

but i want to add more things to say

#

to the bot'

worthy mortar
slate swan
#

then 1

#

i want to add more msg to say to the bot

#

but idk know how

wanton pebble
#

@sick birch i hope you dont mind the ping but are you here?

slate swan
#

@worthy mortar

worthy mortar
slate swan
#

alr

sick birch
slate swan
#

why

wanton pebble
#

well i thought of a better phrasing

#

how would i go around running 2 bots at once on my pc knowing python only lets me run one at a time

#

at the moment i have 2 files using subprocess.call on 2 other bot files

sick birch
#

A better alternative is to dockerize each and use docker-compose up to run both at once

wanton pebble
#

ill try that out, thank you

worthy mortar
# slate swan okay

see if this does what you want:

import random
ArrayOfWordsForBotToAnswer = ['hey','hi','bye!']
LenOfArray = len(ArrayOfWordsForBotToAnswer)
randomNum = random.randint(0, LenOfArray-1)
print(array[randomNum])
slate swan
#

no

#

i ment

#

like

worthy mortar
# worthy mortar

actually @sick birch while you're here,
do you have any tricks for making this text more pretty?

slate swan
#

i wanna add more things to say to my bot

wanton pebble
slate swan
#

no

sick birch
slate swan
#

i mean like i want to make it were if i say hello it will say hello back and i want to make it if i say welcome it will say welcome back

#

in 1 bot

#

and i got the hello one donbe

#

done but i dont know how to make 2

worthy mortar
sick birch
# slate swan done but i dont know how to make 2
@bot.listen()
async def on_message(message: discord.Message) -> None:
  mapping = {
    "hello": "Hello to you too!",
    "Welcome": "Welcome to you too!",
    "How are you?": "I'm doing great, thanks for asking!",
    "What's your favourite colour?": "Mine is green, what's yours?",
  }

  if response := mapping.get(message.content):
    await message.channel.send(response)

This is a pretty complete example, but it's better than an if/else chain

sick birch
worthy mortar
sick birch
#

You can use embeds in regular bot messages

worthy mortar
sick birch
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
worthy mortar
#

okay ill look into that. thanks robin

sick birch
#

Construct one and send it off to your ctx.send()

worthy mortar
sick birch
#

No prob. Feel free to ask with any follow up questions you may have

sick birch
#

It only works if you type in one of those keys exactly, word for word. Capitalization matters

#

It's only an example so I've left a lot of QoL features and improvements up to you. But the basis is there

worthy mortar
slate swan
#

no when i ran it it dint work

sick birch
#

It just depends on what I'm doing. I'll even mix the two up

slate swan
sick birch
#

Good example, a while back I was making a discord bot, discord.py no problem. I also wanted to make a dashboard for my bot, so my users could change things about the bot from the website. I used Next.js, Typescript, TailwindCSS, PostgreSQL, Prisma, and Next-Auth-JS as my tech stack for it

sick birch
slate swan
#

huh

#

can you

worthy mortar
worthy mortar
slate swan
#

like call me and i will screen share

#

@sick birch

worthy mortar
slate swan
#

huh

#

what how

sick birch
sick birch
#

What I'm saying is, copy pasting the code I gave you won't work

slate swan
worthy mortar
sick birch
#

Well you should probably get those red errors fixed

worthy mortar
slate swan
#

yes

sick birch
#

Hover over them, it'll tell you what's wrong

limber bison
#

How can I create Russian roulette, gimme a rode map

sick birch
#

Oh actually looks like I made a mistake

slate swan
#

it saying

sick birch
#

That's embarrassing. That's on me, my fault 😳

limber bison
#

Ohh got it

#

Nvm

sick birch
#

discord.py for years and I still make mistakes like these.. how dumb

limber bison
sick birch
limber bison
worthy mortar
worthy mortar
sick birch
#

Replit?

limber bison
#

Ooo cool , now pls help me too to build one 😳

worthy mortar
sick birch
dull terrace
worthy mortar
sick birch
limber bison
#

Rode map or any sample code

#

So I can get an idea ?

sick birch
#

Here's a roadmap:

#

Step 1: make command
step 2: profit
/j

limber bison
#

πŸ˜‚

worthy mortar
robust fulcrum
# slate swan

Where have you imported discord and discord.ext and defined bot?

sick birch
sick birch
#
  1. Dockerize your app
  2. setup CI/CD
  3. automate the whole process
robust fulcrum
#

I mean for chat . Like muting with time

worthy mortar
#

when i fully program the bot (in 1-2 weeks) you can expect to hear more from meπŸ™‚

robust fulcrum
#

Guys how we can mute a user with time in dpy?

shrewd apex
#

tempmute adds a mute role timeout is a discord feature which is utilised before it was not there thus tempmute was made now that its there its better to use timeout

robust fulcrum
unkempt canyonBOT
#

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

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

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

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

Thanks

#

And time is to be hours or minutes or seconds?

#

Ah ok

slate swan
#

anyone know what package to install to read chrome push notifications It’s not toast as that is used to create notifications, I want to read the pop up message that I get sent from chrome and then send the ctx to a discord channel

robust fulcrum
#

Like i have it time like this 2hr 5mins so how can I convert it to timedelta?

limber bison
#

@robust fulcrum any idea about blackjack or roulette ?

robust fulcrum
#

How?

robust fulcrum
limber bison
#

Game

#

Bj

worthy mortar
# limber bison Game

why don’t you just look up on youtube / google: β€œdiscord python gambling games”

slate swan
#

its a gambling game

#

like poker

slate swan
#

or just look up discord gambling bots, copy one of that

slate swift
#

can someone help with this error

#
import discord 
from discord.ext import commands


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

    @commands.Cog.Listener()
    async def on_ready(self):
        print("Bot is online")

    
    @commands.command()
    async def ping(self, ctx):
        await ctx.send("Pong!")


async def setup(bot):
    await bot.add_cog(ping)(bot)```
paper sluice
#

its listener

slate swift
#
import os
import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix=",", intnets=intents, help_command=None)

async def load():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

async def main():
    await load()
    await bot.start("")

asyncio.run(main())```
slate swift
primal token
#

Quite frankly im not looking for anything

slate swift
silk fulcrum
#

bruh

primal token
#

Have i asked a question?

slate swift
#

You just said you looking for anything

primal token
#

Where exactly?

slate swift
#

Oh I read it wrong, sorry

worthy mortar
worthy mortar
silk fulcrum
#

πŸ’€

primal token
#

Atleast you didnt waste your time looking at Lucas videos

slate swift
primal token
#

youre on 1.7.3 lol

silk fulcrum
primal token
#

bot.load_extension returns None uppon calling it lol

#

i should be a bit more careful with my wording

silk fulcrum
#

you will hurt better discord users? lmao

primal token
#

ok

silk fulcrum
#

ok

slate swift
worthy mortar
primal token
#

How is 6 months not outdated

#

especially with all the changes dpy has had

slate swift
#

I do pip install git+http=s://github.com/Rapptz/discord.py right?

primal token
#

Not exactly

#

you can use pypi

unkempt canyonBOT
slate swift
vale wing
#

http=s:// wtf

slate swift
primal token
#

it wont in an inline block

silk fulcrum
vale wing
#

If you put it into back quotes it won't attach any embeds yeah

slate swift
silk fulcrum
#

... inside the cog init so ...add_cog(Ping(bot))
am i stupid or people sometimes dont read?

slate swift
silk fulcrum
slate swift
#

await bot.add_cog(Ping)(bot)

#

?

silk fulcrum
#

you didn't get that ... here means await bot.?

slate swift
#

No I didn't know if you wanted me to replace or what not

primal token
slate swift
#

What is this guy talking about

primal token
#

im paranoid sorry

silk fulcrum
slate swift
#

I'm still getting this in terminal

silk fulcrum
slate swift
slate swift
silk fulcrum
# slate swift ^

if you mean you replaced it with this then you did nothing except changed ping to Capital letter

silk fulcrum
#

I said to do await bot.add_cog(Ping(bot))

#

this is not same

slate swift
#

I did not see that

silk fulcrum
#

where did you see ) next to Ping πŸ’€

#

(Ping(

slate swift
silk fulcrum
#

burh

#

anyways, does that fix an error?

slate swift
silk fulcrum
#

still same error?

slate swift
silk fulcrum
#

make sure you are using 2.0

#

seems like 1.7.3 where it shouldnt be awaited

slate swift
silk fulcrum
#

how do you run your file?

#

with what command i mean

slate swift
#

Run Python File

silk fulcrum
#

press a run button?

slate swift
silk fulcrum
#

huh

#

try python310 -m pip show discord.py in terminal

slate swift
#

Alright

primal token
#

its python or py on windows

silk fulcrum
#

doesn't it upgrade at least to python3?

primal token
#

either way, you should be checking libraries that can be causing name clashing so you should be checking evey lib installed with pip list

slate swift
#

So do I do python -m pip show discord.py?

silk fulcrum
#

python -m pip list

slate swift
silk fulcrum
slate swift
silk fulcrum
#

github release πŸ’€

primal token
#

yeah, my bad, my command was incorrect

slate swift
primal token
#

You should delete nextcord, discord and discord.py

silk fulcrum
#

well... idk for what do you need nextcord, but alright it doesn't overlap

slate swift
primal token
#

pip uninstall package

slate swift
primal token
#

should invoke pip as a module ofc

silk fulcrum
#

pip nextcord | discord | discord.py pip uninstall -y @slate swift

silk fulcrum
#

woops

#

forgot

#

pip freeze | nextcord | discord | discord.py pip uninstall -y

#

no wait that is trash

#

bruh

#

just remove them manually
pip uninstall -y nextcord
pip uninstall -y discord
pip uninstall -y discord.py

#

and then pip install -y discord.py

slate swift
#

ok

trail phoenix
#

guys i clicked accept accidentaly

#

will i be banned

#

i mean hacked

silk fulcrum
torn sail
#

Probably

trail phoenix
#

what should i do

vale wing
slate swift
silk fulcrum
#

and 2FA too

trail phoenix
vale wing
trail phoenix
#

it closed right in like a sec

torn sail
#

If u didn’t enter/scan anything then u may be fine

silk fulcrum
slate swift
vale wing
#

For sure

slate swift
silk fulcrum
primal token
#

im pretty sure most links redirect you to a look alike and make you sign in to "claim" your free month of nitro

slate swift
silk fulcrum
#

try

vale wing
#

And then they do something like headers interception or smth

slate swift
silk fulcrum
#

πŸšΆβ€β™‚οΈ okay gonna play minecraft, bye guys

primal token
trail phoenix
trail phoenix
#

i changed my password so i should be good

primal token
#

not sure on that but where did it redirect you? send a ss of the page

#

and btw nitro gifts dont use buttons that redirect you to any where lol

mossy warren
#

anyone know why you can't input a user id in the args of msg.guild.ban() command, it says that it needs some sort of clas

trail phoenix
slate swift
#

discord.gift/0137132810123 like that

primal token
#

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

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

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

wdym

#

from what

primal token
#

wait nvm, can you show your error?

mild lava
#

in d.py can i disable reply mentions by default, but be able to specify mention_author=True in replies when i need to?

mossy warren
primal token
mossy warren
#

I want to ban a user with their user id

slate swift
drifting arrow
#

When doing a slash command, how can I set the paramaters to have a placeholder or whatever it's called? in here I want it to be like 'name - type your name'

#

Sorta like how it says 'Introduce yourself'

sick birch
drifting arrow
#

idk if it is lol

drifting arrow
sick birch
#

I’m pretty sure options can also have descriptions

slate swift
#

They can

drifting arrow
#

how?

slate swift
#

I think at least

torn sail
sick birch
drifting arrow
#

I'll use the main description for now. and yeet out an error if it's wrong

torn sail
#

!d discord.app_commands.describe

unkempt canyonBOT
#

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

Example:

```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
    await interaction.response.send_message(f'Banned {member}')
```  Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
sick birch
#

I’m not gonna lie, the documentation for anything slightly involved using app commands is sorely lacking in documentation

#

We have a few basic examples, and the documentation only really describes methods and attributes, not how to use them

#

When I was making my example contributions to discord.py, I had an incredibly difficult time since I was one of the first people to use the new feature (it was the night dpy came back)

#

Lacking documentation is one thing, but not being able to find resources online, or being able to ask anyone else.. god was that a headache

drifting arrow
#

I think my real issue is whenever I try and ask a question, despite completely explaining it in detail, I often encounter trolls.

sick birch
drifting arrow
#

here, and I wouldnt say trolls but more or less people responding with stuff I've already explained doesnt work

sick birch
#

🧐 that’s most likely a communication issue, not your fault though! Communication is so much harder online than it is anywhere else

drifting arrow
#

Probably.

sick birch
#

Being able to convey your question in such a way that it’s crystal clear, and for readers to be able to read everything and not skipping.. requires conscious effort

drifting arrow
#

and that's fine. It's whatever. Frustrating when you have to go around in loops repeating yourself

sick birch
#

Yup and unfortunate there’s no β€œone size fits all” type solution here

slate swift
shrewd apex
#

are there any cases where hybrid_command fails to replace the command deco for prefix command in my code i had prefix commands before and i replace command with hybrid_command and few commands stopped working most of them are working tho

drifting arrow
#

whelp. outside of copying and pasting my Modal classes, I can't seem to figure out how to make them dynamic

torn sail
silk fulcrum
#

more masters

#

we need 3rd

slate swan
#

Has anyone successfully sent push notifications from Chrome to a discord channel? This is not toast right?

silk fulcrum
#

not sure if that is toast or not but anyways Chrome has API

drifting arrow
#

Or you may use a discordbot if there's an API as @silk fulcrum said.

slate swan
#

thanks

silk fulcrum
#

!pypi pychrome

unkempt canyonBOT
drifting arrow
#

I've never used push notifications and still yet to find a use for them so I don't know about it

silk fulcrum
#

not sure if this is the right library... id probably make my own requests

slate swan
drifting arrow
#

or websitename developer

#

there may be an api you can connect to

slate swan
#

ahh i see

drifting arrow
#

It's usually the first thing I do

silk fulcrum
#

yeah if you want to get something from a site that has an API there is no need to go for chrome api

drifting arrow
#

Then from the API, you can create a basic bot that sends whatever data you want

#

I recommend using AIOHTTP btw.

slate swan
silk fulcrum
#

or its some robux miner so you can't send?

slate swan
#

It's java, sec

drifting arrow
#

holy crap this looks like an old af website..

slate swan
#

yeah

silk fulcrum
drifting arrow
#

I didnt even know websites could still look like this

slate swan
#

I been there since 2005

silk fulcrum
slate swan
#

πŸ˜†

silk fulcrum
#

yeah it doesnt seem to provide an api

slate swan
#

but

silk fulcrum
#

however you still can do requests

#

and get raw html code of a page

slate swan
#

this is the IRC

silk fulcrum
#

but but that will be hard to get this text

silk fulcrum
slate swan
#

oh nvm, you need an account

silk fulcrum
#

well, in your case there are 2 options:
try using chrome API
delete this website from your history
i guess

drifting arrow
#

@slate swan out of curiosity.. do the urls look like this: https://djsp.org/trading.php?item=a&item=b?

#

coz you might be able to just do a simple query on the specific items and extract the data

drifting arrow
#

Sure sure.

#

but push notifs are probably just an update on whatever has changed right?

silk fulcrum
#

yeah... like event handler for bots

#

sends what happened

drifting arrow
#

So, if you can query a URL instead and get the same data, does it matter?

silk fulcrum
#

idk

#

i never worked with such curved sites and ideas

drifting arrow
#

me neither.

#

I'm just throwing stuff out there.

silk fulcrum
#

me too

drifting arrow
#

So his options are to either to some form of web scraping, figure out the chrome api thing, or try and do a URL query

slate swan
#

well, some people have made scripts for a game to automate a trade to a user buying items within the site. They have somehow made a script to use the notification of received gold/description. The script then uses what the buyer put in the description to automate a trade within a game

#

surely they are doing this though IRC protocol? idk.....

drifting arrow
#

Β―_(ツ)_/Β―

mild lava
#

can anyone link a discord bot template from the discord.py docs, i cant seem to find one.

shrewd apex
#

he prolly meant some broiler plate

mild lava
#

like some example code

#

lmfao "broiler plate", but yes

#

one where the bot is a class with methods

shrewd apex
#

i don't think there are examples with 2.0 out yet

silk fulcrum
mild lava
#

yeah i made a bot a while ago that has commands as regular funcs

shrewd apex
#

i think he wanted one with subclassed commands.Bot

mild lava
#

but in order to use the new commands you need to await bot.tree.sync()

shrewd apex
#

example

slate swan
mild lava
#

and that can only be done in an async function

#

so....

shrewd apex
mild lava
#

interesting, couldnt find anything about setup_hook for some reason

shrewd apex
#

u can use jsk sync also

mild lava
#

but i got it now

shrewd apex
#

jishaku has a sync command

silk fulcrum
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
silk fulcrum
#

yeah docs has that

mild lava
#

so is it better to use the class-based approach?

kindred kernel
shrewd apex
vale wing
#

Why not recommended lul

#

For dynamic bot updates or smth

kindred kernel
shrewd apex
#

setup hook is called only once so technically for dynamic commands are better

kindred kernel
#

__A__uto __S__yncing (your command tree) __S__ucks, and here's why:
Syncing your command tree automatically causes extra unnecessary requests to be made, this is because you only need to sync when commands are updated.
*see ?tag whensync for a more enunciated list on when to sync.

What syncing does is send your commands to discord for one guild or globally. If you haven't changed your command's descriptions, added/removed commands, changed names, parameters, etc. you shouldn't sync, since you'd only be updating discord with the commands they already have without doing any changes, which is pointless and a waste of an API request to a limit with an already tight rate limit.
*see ?tag whatsync for a more enunciated on what syncing is, and how to do so.

Where should I sync instead?
It's better to sync using a normal (message) command (or even an on_message if you prefer Client) You can even use just a simple eval to do so.
*for example:?tag umbras sync command

*But I don't have the new message content intent... What now?
Bots can still receive message content when the bot is mentioned in it, or in DMs! You could set the bot prefix to commands.when_mentioned

*Why do I get a Missing Access error when trying to sync to a guild? -> See ?tag mas

shrewd apex
#

i just use the jishaku sync command tbh

mild lava
#

what is jishaku?

kindred kernel
# mild lava what is jishaku?

Jishaku -- jsk
A debugging and utility extension for discord.py bots This provides an eval command and much more!

Source: https://github.com/Gorialis/jishaku
Docs: https://jishaku.readthedocs.io/en/latest/

Requirements:

Installation:

  1. Download jishaku on the command line using pip:```py
    pip install -U jishaku

or the dev version:

pip install -U git+https://github.com/Gorialis/jishaku@master
2. Load the extension in your bot code before it runs:py
await bot.load_extension('jishaku')

vale wing
kindred kernel
#

ok

vale wing
#

Idk if dpy does that internally but would be better if it did

mild lava
#

another question, for testing slash commands, its faster to sync to a specific guild, but that creates an issue with duplicate commands, since both global and guild-specific show up in the slash menu then

kindred kernel
#

i did this and had no problems with double commands

#
        self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
        await self.tree.sync()``` this is from gist
mild lava
#

oh so this would only sync to a specific guild?

kindred kernel
#

yes

mild lava
#

alright

pastel finch
#

so I coded a discord bot in repl.it and my main problem is that whenever the word comes in a sentence my bot replies to it. like if i wrote a command to reply good morning to a text with "gm" it will reply good morning when a person sends a text which just contains gm but i want my bot to reply only when somebody says "gm" and not his sentence contains the word "gm"

#

like if somebody says "my weight is 50 kilograms" it replies good morning just cause the text has "g" and "m"

mild lava
pastel finch
#

one sec

pastel finch
#

actually they are like this. like there many words and many replies so it happens in this command

glad cradle
mild lava
#

basically what watchYourCache said

slate swift
kindred kernel
#

what's the problem?

slate swift
kindred kernel
#

do py print(discord.__version__) at the start of file

pastel finch
kindred kernel
#

little python

glad cradle
#

πŸ—Ώ

kindred kernel
glad cradle
#

Master128 > Master86

maiden fable
kindred kernel
#

duck-pond

maiden fable
#

U r still living in 2019 or smth maybe before that

glad cradle
#

I'm the 2019

maiden fable
#

Nice

kindred kernel
#

his living at 0x7e66f0b1f0

maiden fable
#

The latest is 2.0 and u r still using 1.0 nice!

kindred kernel
maiden fable
#

Really?

#

A minor update also?

kindred kernel
#

lmao

dull terrace
#

i need SERIOUS help organizing my code

maiden fable
#

Thought there was only the original 2.0 release till now

kindred kernel
#

nothing changed but danny updated the version on github

maiden fable
kindred kernel
#

so if you download dpy from github it will be 2.1

unkempt canyonBOT
dull terrace
#

this bot is almost up to 5k lines of code and one of the files is 3725

maiden fable
#

Ah, ofc on GitHub its gonna be a greater version

dull terrace
kindred kernel
maiden fable
rugged shadow
kindred kernel
dull terrace
kindred kernel
#

i somehow managed to rewrite my bot

#

well im still doin that

glad cradle
maiden fable
#

My bot.... is on GitHub but still hasn't been rewrote

#

I left it halfway cz idk why

glad cradle
#

send the link of the repo

maiden fable
#

My GitHub is on my profile

#

I don't think I should share the link here

#

The link is in my About Me tho

glad cradle
#

k

tight dagger
#

hi

glad cradle
tight dagger
#

i have moved on from yesterday where i didnt get the bot working

#

but i have a new error

glad cradle
#

send it

tight dagger
#

the bot does read my text

#

2022-08-20 06:28:40 INFO discord.client logging in using static token
2022-08-20 06:28:41 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 36c2593bdf71bc9668c9f6912c9426e3).
We have logged in as CCS#4524
MISTY: (general)

#

it comes blank in console

vale wing
#

You meant doesn't

#

Enable message content intent

tight dagger
#
intents = discord.Intents.default()
intents.typing = True
intents.messages = True
client = discord.Client(intents=intents)
#

is the problem in intents?

#

these are the ones i used

#

@vale wing

deep osprey
#
channel = discord.utils.get(bot.get_all_channels(), id=channel_id)``` is this the correct way to get the channel ID where cmd sent in?
tight dagger
glad cradle
slate swan
deep osprey
#

to add that channel to allowed channels list

tight dagger
# glad cradle in discord.py to be able to use message content intent you need to set ```py int...

i tried this earlier, this is what i get

raceback (most recent call last):
  File "main.py", line 37, in <module>
    client.run(TOKEN)
  File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
    asyncio.run(runner())
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
    await self.start(token, reconnect=reconnect)
  File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 746, in start
    await self.connect(reconnect=reconnect)
  File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 672, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
slate swan
glad cradle
maiden fable
tight dagger
#

ok

glad cradle
deep osprey
maiden fable
#

Haha, the AI part is all done. What I have to rewrite is the client side (the discord bot)

tight dagger
#

@glad cradle dude!!!! thanks a lot. had been jamming my head on this for the past 15 hrs

#

omg

slate swan
# deep osprey how to do that?
@some_bot.command()
async def cmd(ctx: commands.Context, channel: discord.TextChannel) -> None:
    await ctx.send(f"the id is {channel.id}")
    # do something
#

I forgot if ctx is commands.Context or command.Context someone lmk

tight dagger
# glad cradle you're welcome

it said its for bots for more than 100 thats why i didnt really think its necessary. however i did think abt trying it earlier but didnt

glad cradle
slate swan
glad cradle
maiden fable
#

Nice

slate swan
deep osprey
glad cradle
#

have you replaced @some_bot?

deep osprey
#

yes

glad cradle
#

send your code

slate swan
#

how does it the command look now

deep osprey
#
@bot.command()
@commands.is_owner()
async def channel(ctx: commands.Context, channel: discord.TextChannel) -> None:
    await ctx.send(f"the id is {channel.id}")```
slate swan
#

how are you invoking the command

deep osprey
#

!channel

slate swan
#

you need to mention a channel as well

glad cradle
#

that could be a stupid question but are you the owner of the bot?

deep osprey
#

my bad I got it

slate swan
#

what did you do

deep osprey
#

!channel #general

slate swan
#

read the code we send, so you understand it instead of just copying and pasting

glad cradle
#

πŸ¦†

slate swan
deep osprey
#

ok mr.python_learner

slate swan
#

πŸ€·β€β™‚οΈ

mild lava
#

the discord.py docs give this example for a check decorator

def is_in_guild(guild_id):
    async def predicate(ctx):
        return ctx.guild and ctx.guild.id == guild_id
    return commands.check(predicate)

my question is, can i somehow put this inside a class?

#

not sure how to work around the self and @staticmethod stuff

slate swan
#

Okimii can help with that

#

he's a genius

mild lava
#

yeah he is, sadly offline though

slate swan
#

@slate swan πŸ₯Ί

brazen raft
torn sail
mild lava
#

yeah, im probably gonna have to get rid of staticmethod

#

so i need the decorator to access self

brazen raft
#

Why do you

mild lava
#

because a bunch of commands should only run if some self.var is true

brazen raft
#

Is it in a cog?

mild lava
#

yes

brazen raft
#

You can do a cog check

mild lava
#

is that different from regular check?

brazen raft
#

!d discord.ext.commands.Cog.cog_check

unkempt canyonBOT
#

cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.

This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
mild lava
#

oh didnt know about this, thanks

#

wait its for every command in the cog

brazen raft
#

Returns False or True whether to block or allow access to the command

mild lava
#

i only want to decorate some

brazen raft
#

Ok so you need a check that depends on self?

mild lava
#

yes

#

back when i wrote this code i used a regular non-check decorator

    @staticmethod
    def game_command(func):
        @functools.wraps(func)
        async def decorator(self, ctx: Context, *args, **kwargs):
            if self.game_started:
                await func(self, ctx, *args, **kwargs)
            else:
                await ctx.reply("No game started.", mention_author=False)

        return decorator
#

and it works

silk fulcrum
#

before invoke exists, but I don't think it can work for some amount of specific commands

#

is self.var required to be in that cog?

mild lava
#

its set to true and false in some commands

#

basically start_game and stop_game

brazen raft
#

Is it some sort of a cooldown

mild lava
#

so while its false, a bunch of the commands need to be disabled

#

but if you run start_game, then the others are enabled

#

and obviously i dont want to copy-paste this check into every command, that was the whole point of decorators

#

any ideas how i can convert this general decorator into discord.py's check decorator?

silk fulcrum
#

you can probably use cog_before_invoke

#

oh wait... i dont think you can prevent command executiion in before_invoke 😭

#

i thought about smth like thispy async def cog_before_invoke(self, ctx): if ctx.command.name not in your_commands_those_depend: return if not self.var: return

mild lava
silk fulcrum
#

but return won't prevent command from happening

#

os.system("cls") lmao

mild lava
silk fulcrum
#

uhm ok

#

error?

#

how do you connect

mild lava
silk fulcrum
mild lava
silk fulcrum
#

more code, I can't see a problem in code you sent

mossy warren
#

anyone know what the giant ass error is? I didn't change my code and I'm suddenly getting this

silk fulcrum
#

(replit is trash)

glad cradle
#

just run in the shell kill 1 @mossy warren

mossy warren
silk fulcrum
mossy warren
mossy warren
glad cradle
glad cradle
mossy warren
brazen raft
#

@mild lava Does something like this work

@staticmethod
def in_game():
    async def predicate(self, ctx: commands.Context) -> bool:
        if self.game_started:
            return True
        await ctx.reply("No game started.", mention_author=False)
        return False
    return commands.check(predicate)

@commands.command()
@in_game()
async def some_game_command(self, ctx: commands.Context) -> None:
    ...
mild lava
mossy warren
deep osprey
#
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:

    with open('allowed_channels.txt', "a") as f:
        contents = f.read()
    if channel.id in contents:
        await ctx.reply("Already there!")
    else:
        await ctx.reply("Successfully added!")
        f.write(f"\n{channel.id}")
        f.write("\n")``` Why doesn't this code work?
silk fulcrum
#

error?

deep osprey
#

no error

#

it's not outputing anything or adding something to .txt file

mild lava
#

can i make methods into bot commands under the bot class, or do i have to use a cog?

silk fulcrum
#

you exit with ... as f and then use f

silk fulcrum
#

you mean like

async def command(smth):
    def method():
        smth
    smth```?
glad cradle
#

use aiofiles

mild lava
silk fulcrum
glad cradle
silk fulcrum
#

why u need him?

glad cradle
#

does Master64 exist?

silk fulcrum
#

and no hes not

silk fulcrum
glad cradle
#

Cool

silk fulcrum
mild lava
silk fulcrum
#

or can you? 😳

#

@self.command()

deep osprey
# silk fulcrum you should use your `f.write`'s inside the with

so this? ```py
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:

with open('allowed_channels.txt', "a") as f:
    contents = f.read()
    if channel.id not in contents:
        await ctx.reply("Successfully added!")
        f.write(f"\n{channel.id}")
        f.write("\n")            
    else:
        await ctx.reply("Already there!")```
glad cradle
silk fulcrum
#

nah that shouldn't work

mild lava
#

@self doesnt work

glad cradle
mild lava
#

because self is not available in the scope where the decos are

glad cradle
silk fulcrum
mild lava
#

maybe commands.command()?

mild lava
#

like i dont want to go make an entire Core class for a few commands

silk fulcrum
#

but it won't write into the bot

glad cradle
#

whats the command

mild lava
#

(and do this for every bot i have)

glad cradle
#

!pypi aiofiles

unkempt canyonBOT
silk fulcrum
#

well, @bot.command exists

glad cradle
#

πŸ˜•

silk fulcrum
#

right inside the file where you define bot

#

but not inside the bot class

slate swan
silk fulcrum
#

boop beep baap

slate swan
#

!d discord.ext.commands.Bot.add_command

unkempt canyonBOT
#

add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.

This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.

Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")

Changed in version 2.0: `command` parameter is now positional-only.
silk fulcrum
#

imagine command1_callback command2_callback