#discord-bots

1 messages · Page 105 of 1

primal token
#

Robin stop lurking and help

slate swan
#

wait bro let me show you

primal token
#

😡

slate swan
#

i am facing this issue

#
@bot.command(aliases=["Amongus"])
@commands.cooldown(1,500,commands.BucketType.user)
async def amongus(ctx): 
    member = ctx.author
    channel = bot.get_channel(1005776398507581490)
    check = bot.get_channel(1005774386923569213)
    checking = bot.get_channel(1005774410415886378)
    hii = bot.get_channel(1005774465055084564)
    blah = bot.get_channel(1005774489591754822)
    ga = bot.get_channel(1009527767240552489)
    ta = bot.get_channel(1006594487587450972)
    me = bot.get_channel(1010995214325923950)
    if member not in channel.members:
         ctx.reply(" [#1005776398507581490](/guild/267624335836053506/channel/1005776398507581490/)אתה לא יכול להריץ את הפקודה כאן!  אנא נסה להריץ אותה בחדר ")
    if check is None:
       ctx.reply("בבקשה תכנס ללובי!")
    if checking is None:
       ctx.reply("בבקשה תכנס ללובי!")
    if hii is None:
       ctx.reply("בבקשה תכנס ללובי!")
    if blah is None:
       ctx.reply("בבקשה תכנס ללובי!")
    if ga is None:
       ctx.reply("בבקשה תכנס ללובי!")
    if ta is None:
       ctx.reply("בבקשה תכנס ללובי!")
    if me is None:
       ctx.reply("בבקשה תכנס ללובי!")
    else:
      voice = ctx.author.voice.channel.mention
    emibed = discord.Embed(title="מחפש שחקן למשחק אמונג אס", description=f'{ctx.author.mention} Among us מחפש מישהו לשחק! ',color=0x6c97c5)
    emibed.add_field(name="המשתמש נמצא בוויס:", value=voice, inline = False)
    await ctx.send(f" {ctx.author.mention} מזמין אתכם לשחק איתו! <@&890044017776136202>", embed=emibed)```
```[2022-10-12 18:12:04] [ERROR   ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 199, in amongus
    voice = ctx.author.voice.channel.mention
AttributeError: 'NoneType' object has no attribute 'channel'

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 168, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'channel'```
naive briar
#

You keep sending this like 4 times

primal token
#

help him

slate swan
primal token
#

I love how I'm telling everyone to help others when I'm not doing anything kek

wicked atlas
# slate swan

Like we've shown, you need to pass in the intents kwarg, like was shown in that embed, and the other code screenshots you've been sending

unkempt canyonBOT
naive briar
#

The voice can return None iirc

slate swan
#

my bot didnt come even online

#

if member not in channel.members:
what to change it to

wicked atlas
slate swan
wicked atlas
#

You did it here

slate swan
#

i am a fresher

slate swan
slate swan
naive briar
#

Your ctx.author.voice returned None

slate swan
#

i know

#

but thats why it supposed to send if check is None:
ctx.reply("בבקשה תכנס ללובי!")

primal token
#

You should have a check to check if the user is in a guild

slate swan
#

me?

primal token
#

!d discord.ext.commands.guild_only

unkempt canyonBOT
#

@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.

This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
primal token
slate swan
#

@bot.command(aliases=["Amongus"])
@discord.ext.commands.guild_only()
@commands.cooldown(1,500,commands.BucketType.user)
async def amongus(ctx):

#

to try now?

#

AM2i9 you here?

wicked atlas
#

It's requiring you to pass in an Intents object into the intents kwarg

intents = discord.Intents.default()

# Enable the intents you need
intents.members = True

discord.Client(intents=intents)
```If you're new to python, and not just to discord.py, I would stop this and take the time to learn python in general. discord.py is rather advanced
slate swan
#

oh

#

ok

slate swan
wicked atlas
#

!resources

unkempt canyonBOT
#
Resources

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

wicked atlas
#

There are some good ones here

slate swan
#

ohk thanks buddy

undone quiver
#

I want to make a command for my bot that would act as the search bar for my websites

#

How would i do that?

cerulean folio
#

Hi guys, any clue how to use slash commands with python?

cerulean folio
#

it's a library? does it have any down side?

primal token
mighty pilot
#

yea that

#

its baked into discord.py now, but there are other forks that people use as well. but if youve already got something built with discord.py you might as well stick with it to avoid conflict

#

i ran into that problem about a week or so ago

#

Is someone here familiar with MYSQL interactions?

shrewd apex
#

u just mean sql queries no? pithink

#

mysql is sync

#

use an async driver

mighty pilot
#

well, more specifically if i have mydb.close() somewhere in my code is that going to cause disconnect problems? do i have to close the connection at all or can i just use .commit()?

shrewd apex
#

u can just commit after writing in db

mighty pilot
#

alright. wasnt sure if that would cause multiple connections or not

shrewd apex
#

are u using a single connection across whole code or making connections throughout

mighty pilot
#

single connection for the whole code then using cursor to execute throughout the code

shrewd apex
#

coz if u close when u are using a single connection then the connection is closed across the whole bot

north escarp
#

!discord.timeout

shrewd apex
#

just use asyncpg

mighty pilot
#

ah alright. thanks

shrewd apex
#

and enable autocommit

sick birch
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 [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

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

ive already got more than half my project written with commit at the end of my work, not going to mess with it lol

north escarp
#

@sick birch do I need to install a module for it?

ember nest
#

Can someone help me

#

About my level system at bot

#

Why not working

naive briar
#

Tell the problem

ember nest
#

If someone can help me to fix my level system come to #help-honey

north escarp
# sick birch Only discord.py

and if you put timeout on the mute command, will it be possible to set your own time for which you want to give mute ?

slate swan
#
async def invite(self, ctx):
    em = discord.Embed(color=000000)
    em.add_field(name="Invite Divine")
    em.set_footer(text="[]()")
    await ctx.send(embed=em)```
#

anyone know why this doesnt work?

#

you didn't close the bracket of the Embed object

glad cradle
slate swan
# glad cradle show your full cog not just a part of it
from http import client
import random
from secrets import choice
import discord
from discord.ext import commands
import os
import asyncio

class Utility (commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

@commands.command()
async def invite(self, ctx):
    em = discord.Embed(color=000000)
    em.add_field(name="Invite Divine")
    em.set_footer(text="[]()")
    await ctx.send(embed=em)

async def setup(client):
      await client.add_cog(Utility (client))```
#

bad indentation

shrewd apex
#

http

#

kewl

ember nest
#

Can I get money by making bots ?

shrewd apex
#

yes

slate swan
ember nest
shrewd apex
#

by economizing your bot content

#

and see if ppl are willing to pay

ember nest
shrewd apex
#

...

slate swan
# slate swan ?

stop ?ing and speak what part of "bad indentation" you don't understand

shrewd apex
#

that too ig making bots for others

slate swan
shrewd apex
#

wrong u dont understand python

#

!indents

unkempt canyonBOT
#

Indentation

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

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

Example

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

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

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

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

ember nest
slate swan
ember nest
shrewd apex
#

indents are like first step towards python

#

bro stop pinging each time

ember nest
#

Lol sorry

slate swan
#

bros mad over a ping

#

🤡

shrewd apex
#
  1. You make a bot lets say an example economy bot where u have coins now u can make coins pay to get this is economizing ur bot
  2. Others want to make bots but sometimes lack time or skill so u make bots for them and they pay u
#

there maybe other avenues for earning but idk

shrewd apex
slate swan
#

or stop thinking of earning thru bots
don't want to sound mean but thats probably the worst way of getting paid. every next person i see is a bot developer 🗿who is ready to work for money.

ember nest
#

I just make bots for fun and cuz I like it

slate swan
#

indirectly it revolves around "pay to get <x> thing"

ember nest
#

Oh yeah I understand

slate swan
#
    async def invite(self, ctx):
        embed = discord.Embed(title="Invite Divine", description=f"[]()", color=discord.Colour.black())
        embed.set_footer(text="{name} Made this Embed")
        await ctx.send(embed=embed)```
#

why does it say

#

there's no black color attribute

#

you can just use the hex

#

it was 0 iirc

#

when i do that its an error

#

im trying to do 18191c

#

it would be 0x18191c

#

i want the embed to be the same color as discord dark mode

#

always add 0x before hexs and don't call it

#

so 0x18191c

#

doesnt work

#

show updated code

slate swan
# slate swan show updated code
    async def invite(self, ctx):
        embed = discord.Embed(title="Invite Divine", description=f"[]())
        embed.set_footer(text="{name} Made this Embed")
        await ctx.send(embed=embed)```
#

oops

#

i don't see anything related to color.here

#
    async def invite(self, ctx):
        embed = discord.Embed(title="Invite Divine", description=f"", color=0x18191c())
        embed.set_footer(text="{name} Made this Embed")
        await ctx.send(embed=embed)```
slate swan
#

remove the ()s after it

slate swan
#

now you removed the 0x too 🙂

slate swan
slate swan
# slate swan u told me to

i asked to not call it? if you don't know what calling an object in python means you seriously need to learn more

#

rewrite the code again it will work

#

this error happens when you mix tabs and spaces, just rewrite with any one of these will fix it itself

north escarp
#

@slate swan and in order to make a timeout in mute, you need to write a time variable and a reason variable into it ?

slate swan
#

add 0x and remove () ... how can i put it more simply?

slate swan
slate swan
# north escarp yes

you do need to provide a datetime or timedelta in the timeout method, but reason is optional

north escarp
slate swan
#

no

#

await member.timeout(datetime/tinedelta object here, reason="reason")

#

!python

#

what is the name of the second line?? footer? description?

finite salmon
#

Send the whole embed

#

Most probably description

slate swan
#

i did the invite part

#

i just dont know the 2nd line

tidal hawk
#

This thing?

slate swan
finite salmon
#

If you're using dpy it's value attribute under add_field

slate swan
#

not this

slate swan
slate swan
finite salmon
#

embed = discord.Embed(description="test").add_field(name="Invite", value="what ever you want here")

#

This is an example

finite salmon
#

Oh

#

Wait

slate swan
fading marlin
finite salmon
#

one sec I get what you mean

slate swan
slate swan
slate swan
# slate swan

im trying to do this i have the invite part the title and the footer just not the 2nd line

finite salmon
#

embed= discord.Embed(title="Invite", description="whatever you want here")

#

I suppose that's what you want

finite salmon
#

Then

fading marlin
# slate swan

"Invite" is an embed title
next 2 lines are the description
last line is a footer

slate swan
finite salmon
#

If you want to make a new line just do \n inside the string?

finite salmon
fading marlin
#

^

slate swan
#

im confused

finite salmon
#

I suppose you're trying to use multiline string?

slate swan
finite salmon
#

And just add whatever you want and it'll pop up in another line

slate swan
finite salmon
#

Yes, and now add whatever you want after \n

slate swan
#

after the \n

finite salmon
#

The purpose of \n is to make a new line for a string in the compiler (here it's your bot) without you having to actually do it in your code

finite salmon
#

I think I get what you mean

slate swan
finite salmon
#
embed = discord.Embed(description="This is line 1\nNow this is line 2, hope this explains it")
#

You just slap a \n inside the string without adding another description and it'll create a new line for you

finite salmon
slate swan
finite salmon
#

My pleasure

slate swan
finite salmon
#

No sorry

#

Maybe you could take a ss of your screen and paste it in a painting app an use the colour picker tool, and with that you could find the hex? Maybe?

#

Idk it would be too much work lmao

slate swan
#

imma just ask somsone

#

someone

#

yea i found it out

sick birch
unkempt canyonBOT
#

classmethod dark_theme()```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a value of `0x36393F`. This will appear transparent on Discord’s dark theme.

New in version 1.5.
sick birch
#

it's built in for you

slate swan
#

do u know api which returns images from given text (not including imgur)

#

!pastebin

unkempt canyonBOT
#

Pasting large amounts of code

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

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

slate swan
#

can someone help

glad cradle
#

show the full traceback

slate swan
glad cradle
#

no

#

i mean show the full error

slate swan
sick birch
#

I doubt it, python errors don't start with an indent

slate swan
sick birch
#

They're also usually not that short unless you have a really bad error handler set up

sick birch
slate swan
sick birch
#

Scroll please?

slate swan
#

cant scroll

sick birch
#

Hit the up arrow, then enter and run the script again

#

That should reset the buffer

slate swan
#

ok i got it

#

imma send error in pastebin

sick birch
slate swan
#

i got rid of and now this is the only error

#
  em = discord.Embed(colour="0x36393F"(), description=f":approve: {context.author.mention}: Set the slowmode delay to **{seconds} seconds** in {context.channel.mention}")```
sick birch
#

why are you calling the string

#

this is the darkmode embed color, yes?

#

just use discord.Colour.dark_theme()

slate swan
stone quest
#

yo is there a parameter parser i can use when handling message content?

#

ping me with response or need more context - thanks!

finite salmon
# slate swan

Just a suggestion, it's a good practice to use is keyword when you're checking if a variable is of None type and the same goes to booleans. So instead of member == None, do member is None

#

Although both works it's a really good practice to use is in right cases

stone quest
finite salmon
#

Here he as predefined member to be None if user is not mentioned not true or false

stone quest
#

not member also works for None

#

since none is false

finite salmon
#

Oh

#

Normally I would just do is not None

stone quest
#

well there is a shorter way for you, either works just what you prefer yk

finite salmon
#

right

mighty pilot
#

in reference to slash commands, is there a way to say - if no optional arguments are provided, do this

sick birch
#

I believe the default value is None if you set it to optional, so you can check if arg is None: ... and do something

feral frost
#

how can i play sound in voice chat ? i can let my bot join but cant play a simple part of sound

mighty pilot
mighty pilot
slate swan
#

if all(arg1, arg2....) will be False if any of them is None

sick birch
mighty pilot
#

i want to check if all arguments are none

sick birch
#

Then yeah do as sarth said

bright wedge
#

Where is the problem

sick birch
#

Though if you're just going to send a message telling the user to include the arguments, you may as well just make the required and handle the errors seperately

#

I see too often people making arguments optional only to tell the user it's not optional

#

A bit counterintuitive if you ask me

mighty pilot
#

is there a way to make any 1 of the arguments required? id like for them to be able to set one variable or all if theyd like so theres 10 optional ones

slate swan
#

just use a slash command at this point

mighty pilot
#

so i have an if statement for each not being None, and i was just going to send a message saying they need to include 1 argument if they dont

mighty pilot
slate swan
#

yeah then you can set all arguments as optional

mighty pilot
#

i did

slate swan
#

and then check if all args are None, if they are then raise your error

#

you can use if not any(arg1, arg2...): for that

#

!e ```py
a=None;b= None
if not any({a,b}): print("use atleast 1 arg")

unkempt canyonBOT
#

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

use atleast 1 arg
mighty pilot
#

yea i was trying to avoid listing all the arguments to make it look nicer if possible but ill probably do that. thanks

mighty pilot
slate swan
#

!d discord.Interaction.data

unkempt canyonBOT
slate swan
#

yeah should work

mighty pilot
#

well if an argument is provided then it responds to the interaction with a message saying the variable was updated

slate swan
#

could you show ur code

mighty pilot
#

well, i guess its not technically a response, if a variable is updated it sends a message in the channel for each variable provided. providing code in this case is easier said than done. im on a remote vm that doesnt let me copy paste outside the window

slate swan
#

its not a response then. you actually need to use interaction.response to create a response

mighty pilot
#

hmm alright

mighty pilot
#

alright onto the next problem im having. i have an on_message event and during that i grab the message.guild.id. however, when an ephemeral message is sent i cant grab that object. how can i handle that attribute error if message.guild comes back as NoneType

#
    guild=message.guild.id
    if message.author.bot == True:
        return
    else:```
slate swan
#

Question, I'm using walk_commands and recieve a groups subcommands as expected.
ex: ?role humans
I recieve humans and any other subcommands within that group.
But humans, is also another group with the subcommand remove
ex: ?role humans remove
Is there a method that can retrieve both role , humans and the commands within humans?
I want to retrieve it as role humans remove

dull terrace
#

or message.guild

#

whatever is returning None

mighty pilot
#

It's saying message.guild doesn't exist for an ephemeral message therefore .id can't be none

#

Because it doesn't exist

dull terrace
#

yeah then check if message.guild is None

#

if it has no guild you can do hasattr(message, "guild")

#

i assume it would still have the attribute though, i've never tested with ephemeral stuff

mighty pilot
#

for some reason it doesnt, idk. check for message.guild works, thanks

pulsar bay
#

is it possible to use these brackets {} in a f-string without making it work

pulsar bay
#

like i want to use {usermention} without making it a f string but I NEED an f-string

rugged shadow
#

{{usermention}}

#

double brackets will equal to one literal bracket

unkempt canyonBOT
#
Nuh-uh.

No documentation found for the requested symbol.

#
Fat chance.

No documentation found for the requested symbol.

rare echo
fluid shadow
#

Is there a way I could make like a grid of buttons for a minesweeper type of gamemode?

hushed galleon
#

sure, just know that discord only allows 5 buttons per row and 5 rows per message

slate swan
sick birch
#

its 5

#

5x5 grid of buttons for a 25 max

hushed galleon
#

ive tried minesweeper with select menus to manage larger grids, but its a bit clunky having to click up to 4 times to select a cell

#

another bot i played with used two messages for a 5x10 grid, though they didnt edit one of the messages through the interaction directly so it hits the edit ratelimit pretty fast

pulsar bay
#

how would i make my bot leave every server under 15 members

slate swan
# pulsar bay how would i make my bot leave every server under 15 members

Loop over all guilds in bot.guilds and then check the total members, if lower than 15 make the bot leave the server. Reading and searching in the documentation will help to find the appropriate attributes and functions.

You can also use the event that is triggered when the bot joins a server - simply check again if the total members is below 15 and leave if it's the case - so that you won't need to do that manually in the future.

ionic garden
#

so

slate swan
#

Define "interactions"
• Buttons are interactions
• Slash commands are interactions
• Modals are interactions
• Select menus are interactions
• ...

And what have you already tried?
If you've tried nothing then maybe you can try researching on your own using the documentation and looking at the examples here https://github.com/Rapptz/discord.py/tree/master/examples

ionic garden
#
        yes = discord.ui.Button(label="Yes")
        async def yes_callback(i: discord.Interaction):
            nonlocal execute
            execute = True
        yes.callback = yes_callback

        no = discord.ui.Button(label="No")
        async def no_callback(i: discord.Interaction):
            nonlocal execute
            execute = False

        no.callback = no_callback

        view = discord.ui.View()
        view.add_item(yes)
        view.add_item(no)
        await ctx.send(ctx.author.mention, embed=embed, view=view)
#

ok so uh
i have a message that just asks "yes" or "no"
if "no", deletes the ask message and yeah yeah
if "yes", performs the action

#

pretty simple, but i've no clue how to actually do it

slate swan
ionic garden
#

kk

#

is there a more "quick-n-dirty" way to do it?

#

don't wanna make an entire class just for confirmation

slate swan
#

That is the way of doing it

ionic garden
#

bluh

rugged shadow
#

should I use try/except in commands?

slate swan
#

You can, I'd rather use appropriate error handlers

rugged shadow
#

but why?

#

the only case where my command would throw an error is this one line

slate swan
#

Because you maybe don't want to have always the same try/except when you can put it in one single global handler

rugged shadow
#

it's a specific error

slate swan
#

Yeah then as said, you can use them

slate swan
#

so I am running a boost bot but I am getting this erorr and the server id for KeyError is right i double checked anyone know why?

#

Well, key cannot be right otherwise you wouldn't get that error...

#

Furthermore, without code we can't help properly but just take random guesses

stable path
#

How do I get my bot to store an if statement trigger as a variable?

#

Because people can roll dice right now but they can’t add any modifiers.

#

And I want to make it so it’s possible to add modifiers in the same message.

#

So even if they roll d20 or a d20+1 it calls the same if statement but calcs it differently depending on if there is a + or not.

slate swan
slate swan
#

There's nothing secret just using public library

#

people sell the code for $100

#

im serious

#

Selling for 100$, pathetic

#

some othes sell for $60

#

Whatever, share only the part where the guild ID is used

#

Probably like 1-2 lines

stable path
slate swan
slate swan
#

Then where it's linked to that specific error

stable path
#

Or maybe I could add a nested if statement?

slate swan
#

Otherwise yeah, shoot me a DM I'll take a look in some time

slate swan
#

Slash commands

slate swan
#

its a boost bot tho

#

Make sure you put IDs as integers, not strings

#

also whatever update_guild_commands is probably doesn't work

#

That's in the library itself

#

dpy? no its not

#

Read the traceback

#

It's internal code within the library

#

Nothing user controlled

#

there is no traceback relating to what that function actually is. the only info from the traceback is all dpy stuff lol.

#

And that's my point

#

They are using guild IDs somewhere that is used by that function

#

Since they wrote it wrong, it errors within code from the library itself

#

So yes, update_guild_commands works perfectly fine

stable path
#

@slate swan do you know if there is any way when an if statement is used to store the message that started the if statement as a variable?

slate swan
#

IF given the correct settings

#

also whatever that code is in literally on github lol

slate swan
#

you sure?

#

Yeah it's internal

#

As said countless times

#

these are the only two places where update is written

#

its literally dpy

stable path
#

Guess I turned on invisibility or something.

slate swan
#

The issue is that you're using guild IDs incorrectly

#

As said, make sure they are integers and not strings

#

hmm

#

I'll look at your code in some minutes

stable path
#

I know my question is probably pretty basic but to not even validate a response is just cold.

slate swan
#

If nobody responds either nobody CAN or you have not asked in a way that is understandable with examples or similar.

#

Not responding if people can't is not being cold, it's just not sending random pointless messages that flood the chat

stable path
#

await get_context(origin, /, *, cls=...)

#

Would this library call work?

slate swan
#

Not with parameters like these I suppose

stable path
#

The idea is for it to store the initial message sent that activated the command.

#

Then I am going to try and use regex to split the message into two parts.

#

Then use the second part and apply it as a modifier to the base result.

#

But the issue is I don’t know how to do that first part.

slate swan
#

@slate swan
config.json

"guildID": "1018396160274223124"

bot.py

guild_ids=[settings["guildID"]]

As said, IDs are integers - so remove the quotes from the JSON so that it's an actual integer and not a string

#

Has been changed to that quite some time ago

#

when was it changed if you dont mind me asking

slate swan
slate swan
#

im getting this now

slate swan
#

Well not so old since it uses slash commands

#

Just non tested code

#

Though @bot.slash_command never existed or is old code before v2.0

#

So I wouldn't really bother fixing the code, as you'd most likely need to rewrite almost everything as it's super old and unsupported code

#

hmm

#

You need to define bot.session = ... somewhere, take a closer look at the bot, RoboDanny, you've copied this code from they most likely have that somewhere

unkempt canyonBOT
#

bot.py line 123

self.session = aiohttp.ClientSession()```
slate swan
#

That is what you haven't copied

#

That , doesn't belong here - remove it

slate swan
slate swan
slate swan
slate swan
#

Actually you got completely scammed but yeah

#

The code is public

#

So you got sold something you can download for free on GitHub bravemmlol

#

The channel is not in the bot's cache

#

Hence you need to use something like

c = interaction.client.get_channel(...) or await interaction.client.fetch_channel(...)

So that it will first try to get the channel from cache, otherwise fetch it with an API call

#

Exactly, only the first part of the code

#

The or is part of Python

#

It's not "do that or that" in english

#

Python will try the first method, if returned None will use the second part

#

As the second part is only needed to be used if the first part resulted to None

#

Correct, should do the trick

#

So looks like the code you've shown in red, will only be executed when executing the command

#

You'd need a on_message event and check within that event if the user was AFK

#

Can't you directly select the reason?

#

And forget about the SELECT userID FROM ...

#

Then if it found something in the AFK table, send a message saying the user is AFK

#

I'd just use a SELECT reason FROM afk WHERE ...

#

Basically just keep the lower part and remove the part above

#

Basically, just make a query to SELECT reason FROM afk WHERE ...

#

If it found something, send a message

#

Otherwise, do nothing

#

Remove everything related to AFK and recode it, with what said above

#

You will figure out what needs to be kept and what needs to be removed

#

My guess is that you just need that part

#

Then if it found something, send a message

#

And I recommend you to one day switch at using cogs, so that you don't have a 4k+ lines bot.py file

#

Things that are not needed, yes

#

Keep things like async with ...

#

As these are needed for the database connection and queries

#

I'll go back at working kryptonWriting

#

That is not necessary anymore

#

The else at the bottom is wrongly indented

#

Should be

if result1 is None:
  return
else:
  # Send your message here
#

Or, you can just do

if result1 is not None:
  # Send your message here
#

Inside the if you can keep them

#

The if (member1.id, ) in member is not necessary anymore

#

So you will need to fix the indentation

#
member1 = message....
await cursor.execute(...)
...
if result1 is not None:
  # Send your message here

That's about all you need

#

The else is wrongly indented, should be same level as the if

slate swan
#

Right now you're sending the message if there was no member mentioned in the message

#

And result1 is not defined in that scope, so it should error at the moment

#

Indenting it accordingly will do the trick

#

Yeah that looks better

eternal turret
#

Is it possible to get the data of all of the messages sent by a person in another server as a csv or something similar?

slate swan
#

It is, though that seems like against Discord's Developer Policy

#

That case use some print to see where it stops, ignore the lower part for now

#

In your SQL, use userID={...}

#

Not sure if that will fix, but I remember having issues with that myself

#

3956

#

And also message.author.avatar.url for 3967

naive briar
#

!sql injection

unkempt canyonBOT
#

SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
PEP-249 - A specification of how database libraries in Python should work

slate swan
#

No, you have userID = {...} and not userID={...}

#

Though you should get errors

#

Nonetheless use some print to debug where your code doesn't work as intended

#

Yeah ignore the welcome back for now

#

Focus on the part above

#

The part below will never be executed because of that

#

And you need to indent it outside of the if len(message.mentions) > 0 as you also want to send the welcome back message if there was no member mentioned in a message

#

Remove it

#
if message.guild is None:
  return
if len(message.mentions) > 0:
  member1 = ...
  [...]

# Your welcome back code
await cursor...
[...]
#

Indented one more to the left

#

Currently you will only execute the welcome back code if there was a member mentioned in a message

#

Yeah like that

#

Also I do believe that

if message.guild is None:
  return

is not needed at all

#

As you already similar above

#

Don't need the lavender part

#

Correct

#

Well, any errors? Any prints not executed which should be? etc. etc.

#

Ah yeah

#

That is printed though

#

Is that getting printed?

#

Yeah, enable the message_content intent

#

!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 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.

naive briar
#

Do you have all of the intents enabled? Or you're having multiple on_message events?

slate swan
#

No need of the members but the message_content is needed

#

In code and developer portal?

#

Then check if you don't have other events of the same

naive briar
#

!d discord.Intents.messages

slate swan
unkempt canyonBOT
slate swan
#

Only one of them will work bravemmlol

#

Other ones will get skipped/ignored

naive briar
#

!d discord.ext.commands.Bot.listen - Then use bot.listen instead

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").

Example...
slate swan
#

Now consider using cogs PepeHmm

#

Sure, gonna take my break

#

Bot doesn't have the permissions to edit members

#

Bot is trying to edit the nickname of someone it can't edit

#

You're probably owner

#

Test with another account

#

Oh yeah and when selecting the reason for AFK etc. consider also checking for the guild ID and not just the user ID

#

So like SELECT reason FROM afk WHERE userID={...} AND guildID={...}

#

So that you get the AFK reason of the user in the current guild

#

I'd rather use message.guild.id

#

Other than that seems fine

#

Errors or they are gone now?

#

Yeah the bot still doesn't have the permissions to edit the nickname of the user

#

As I said, create a new account and use that one for testing

rugged shadow
#

are you checking for AFK using the username? lol

slate swan
#

No

#

The bot still will never have the permissions to edit the nickname of the owner of the server

#

Create a new account and use it for testing, takes 60 seconds to create an account

#

Or yeah, don't edit the nickname

#

And in your DELETE statement at line 3973, remove the whitespaces

#

userID={...}

#

Yeah remove it for now, you can always add it later again

#

In your select at 3969 also check for the guildID

#

You probably have an AFK status in another guild ID and since you're not selecting for the specific guild it will always return one

#

Shouldn't take too long, go on

#

Right, so one issue is that you're adding the reaction to msg

#

And you're overwriting message

#

So remove lines 3823 & 3824

#

And add the reaction to message

#

Which is the case right now

#

And when using

async def on_message(message):

don't create variables like msg or message in your code, keep it clear which variable is what

#

Yeah, that's not needed

#

Correct

#

And when you send a message and want to delete it after some time, use

await message.channel.send("Hello world", delete_after=5) # Will be deleted after 5 seconds
#

Correct

#

You can also delete these two

#

Just replace with await message.delete()

#

As that will delete the original message sent by the user

#

That is also unnecessary, just put the emoji directly in the parentheses

#

Yeah, so that you keep the same format as your other events

#

I'd rather replace every msg to message

#

as you've used that before in other events

#

To keep consistency

#

No need of the .delete()

#

No need to assign it to a new variable either now

#

After that check the current status

#

And yeah, remove the whitespaces in your queries

#

number=...

#

3824

#

Yeah, since you used delete_after

#

Sure

#

And use some print if to debug as always

#

remove whitespaces and add some print

slate swan
#

Yeah that error is kind of normal

#

See at line 3807 you're checking if result2 is none

#

If it's none, then at line 3809 you're getting the index 0

#

Which will never work as it's None

#

Don't understand what you're checking there

#

You can also remove line 3810 and 3811 as you already have that at line 3786 and 3787

#

Well, if result2 is none then you just want to insert and react accordingly

#

You don't want to update, don't want to check if the user was the same

#
if not result2:
  # Check if it's "1" then insert and react accordingly
else:
  # Check if playing alone, update and react accordingly
#

Just put everything else than insert stuff outside in an else

#

Put the if result2[0] == message.author.id and if result2[0] != message.author.id in a new else statement

#
if not result2:
  # Insert stuff
else:
  if result2[0] == message.author.id:
    # Your stuff for playing alone
  else: # Same as 'if result2[0] != message.author.id'
    # Your stuff for updating and reacting
#

Line 3809 to 3814 should be in the else

#

There is no reason on checking if they're playing alone when it's the first message sent

#

You also don't need

alone = ...
await alone.delete()

just do await message.delete()

#

in the else

#

Not outside of it

#

And in your insert

#

You probably want to insert number as well

#

And set it to 1, unless you've added a default value in the schema

#

if you've set a default value, which you should, that's fine

#

Yeah

#

line 3822 is elif though

#

where you insert

#

No need of an argument

#

First number is always 1

#

3823 also elif

#

Small off topic question, have you even learned Python

#

No need to read the docs for basic Python

#

I won't, just been wondering

#

That case I recommend learning more

#

Yeah so about that, just insert 1 directly instead of using %s

#

Yeah probably better, remove number though at 3806

#

Yeah that one

#

Yeah because you probably have old rows in the database

#

Need to clean that up

#

If it's hosted somewhere there's most likely an online management system you can use

slate swan
#

What is even ApplicationContext

#

Ah okay, weird decision

#

Well that case it's ctx.user or ctx.author not ctx.member

#

I'll eat

tough lance
#

A bit off topic but like really?

slate swan
#

Something like 15k+

true salmon
#

It only took like 3 weeks to fix the bug causing the entire bot to crash when a command that uses anything that can only be done in a guild in DMs

slate swan
#

Look the positive side: You fixed it

true salmon
#

I just realized

#

I need someone without permissions to run a command

slate swan
#

UD81_codm_xdoubt There's a 0 too much here

#

You're using fetchone()

#

So it will always return only one

#

Yeah pretty much

#

it will return all

#

Well that's normal

#

You need to loop of the results now

#

As you don't have only one result

#

A for loop over the results

#
for x in y:
  x[0] # First column of each result
#

Well y needs to be a list

#

item returned by .fetchall

#

No

#

fetchall() returns your list needed

#

So loop over that

#

Then you need to append the role to a string or new list to be able to display them all in the embed at once

#

!e

y = [1, 2, 3]
z = ""
for x in y:
  z += f"{x}\n"
print(z)
unkempt canyonBOT
#

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

001 | 1
002 | 2
003 | 3
slate swan
#

That's when actually knowing Python becomes handy

#

Copying code won't help you in learning

hallow kernel
slate swan
hallow kernel
#

z = "\n".join(map(str, y))+"\n"

slate swan
#

As far as I remember, [1, 2, 3] is not a list of strings

#

Yeah, and that's absolutely horrible

hallow kernel
#

ok

slate swan
#

Make your entire file a one liner to make it look cool at this point

hallow kernel
#

y is there list builder and no string builder

slate swan
#

!e

print("didn't knew py")
#

!e

print("didn't knew py")
unkempt canyonBOT
#

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

didn't knew py
primal token
#

ok

slate swan
#

get_member is not a coroutine, so you don't await it

lost yoke
#

how do i make selected images, when run the command, be randomly sent?

slate swan
#

random.choice()

#

And pass along as argument a list of images you want to send

lost yoke
#

inside the parentheses?

slate swan
#

Yeah x2

lost yoke
#

by url?

finite salmon
#

When do we use fetch_member and get_member? Do they have their own uses?

slate swan
#

You can give anything you want, can give a list of string URL or a list of objects doesn't matter

slate swan
#

get_ gets from cache, if it's not in cache it will return None

#

fetch_ makes an API call

slate swan
#

Yeah, but pass a list

lost yoke
#

Explain.

finite salmon
slate swan
#

!e

import random
x= ["url 1", "url 2", "url 3"]
print(random.choice(x))
unkempt canyonBOT
#

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

url 2
slate swan
#

More basic python knowledge is not doable

lost yoke
#

thanks

slate swan
#

^

finite salmon
#

Thanks

slate swan
#

Usually doesn't really matter as you'd use

x = get_xxx(...) or await fetch_xxx(...)
finite salmon
#

👍

lost yoke
#

x= ["<https://tse2.mm.bing.net/th?id=OIP.5Ks1dLss5GbwhfKPee1yjAHaE8&pid=Api&P=0>", "<https://tse1.mm.bing.net/th?id=OIP.Ly8dLGPXJ5mx3aVw88mUKgHaE1&pid=Api&P=0>"] await interaction.response.send_message(f"", ephemeral=False)

#

I did, how do I put it to send in chat?

#

@slate swan

slate swan
#

!f-strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate swan
#

Once again, most basic and fundamental knowledge

#

Need better/longer traceback

#

You're trying e.g. x[0] on a SlashCommand object

lost yoke
#

sorry, iam from brazil

slate swan
#

Well

#

Most likely because you have a slash command named list

#

Which is a reserved keyword

#

And should not be used for function name e.g.

#

Otherwise you overwrite it and that's not good

#

Just name it job_list

#

That's fine, just don't have a function or similar named list

#

Good

@bot.commands(name="list")
async def job_list()

Not good

@bot.commands(name="list")
async def list()
#

Yeah - change list to job_list

#

And you can set name="list" in the decorator as shown above

#

I'd usually recommend to use job_list etc. for every command

#

You might have one day for example items list command

#

So you can't name it just list as well

#

Instead it would be items_list

#

To keep it unique

#
class system(discord.ui.View):
    def __init__(self, user):
        super().__init__(timeout=None)
        self.value = None
        self.timeout = None
        self.user= user

    @discord.ui.button( label="Other Games", style=discord.ButtonStyle.blurple, custom_id="other_games:blurple")
    async def system(self, interaction: discord.Interaction, button: discord.ui.Button):
      await interaction.response.send_message(view=TicketView)

class TicketView(discord.ui.View):
    def __init__(self, user):
        self.user= user
        super().__init__(timeout=None)

    
    @discord.ui.select(placeholder="Choose a role!", options=[
        discord.SelectOption(
            emoji="![1CounterStrike](https://cdn.discordapp.com/emojis/569987371538579456.webp?size=128 "1CounterStrike")", label="Counter Strike", description="Choose me if you want to be updated when someone wants to play CS!"
        ),
        discord.SelectOption(
            emoji="![valorant](https://cdn.discordapp.com/emojis/870290237530705973.webp?size=128 "valorant")", label="Valorant", description="Choose me if you want to be updated when someone wants to play Valorant!"
        ),
        
        discord.SelectOption(
            emoji="![cds](https://cdn.discordapp.com/emojis/1030088005786021899.webp?size=128 "cds")", label="Haxball", description="Choose me if you want to be updated when someone wants to play Haxball!"
        )
    ])
    async def help_callback(self, interaction: discord.Interaction, select):
        select.placeholder = f"Reason: {select.values[0]}"
        reason=select.values[0]
        if reason == 'Counter Strike':
            
            role=get(interaction.guild.roles, id=1030085444534292560)
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
                await interaction.response.send_message(f"Chooses Counter Strike Succssesfully!", ephemeral=True)
        if reason == 'Valorant':
            role=get(interaction.guild.roles, id=1008808500744441876)
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
                await interaction.response.send_message(f"Chooses Valorant Succssesfully!", ephemeral=True)
        if reason == 'Haxball':
            role=get(interaction.guild.roles, id=1030085098600669195)
            if role in interaction.user.roles:
                await interaction.user.remove_roles(role)
            else:
                await interaction.user.add_roles(role)
                await interaction.response.send_message(f"Chooses Haxball Succssesfully!", ephemeral=True)


@bot.command()
async def sys(ctx):
    view = system(ctx.author)
    embed=discord.Embed(title="**רוצים לדעת ראשונים כשמישהו רוצה לשחק?**", description="מוזמנים לבחור אחד מהרולים המופיעים כאשר אתם לוחצים על הכפתור! \n תהנו!")
    embed.set_footer(text=f"Requested by {ctx.author}")
    await ctx.send(embed=embed, view=view)```
and when i tap on the button
```[2022-10-13 15:14:01] [ERROR   ] discord.ui.view: Ignoring exception in view <system timeout=None children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Other Games' emoji=None row=None>
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 224, in system
    await interaction.response.send_message(view=TicketView)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 703, in send_message
    params = interaction_message_response_params(
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 578, in interaction_message_response_params
    data['components'] = view.to_components()
TypeError: to_components() missing 1 required positional argument: 'self'```
#

what do i do then

#

oh i will try

#
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 273, in sys
    view = system()
TypeError: __init__() missing 1 required positional argument: 'user'

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 168, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'user'```
#
await interaction.response.send_message(view=TicketView)
#

Have you tried adding () after TicketView

#

Just like you do on the sys command

#

OH

#

i will try

slate swan
# slate swan Have you tried adding `()` after `TicketView`
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 273, in sys
    view = system()
TypeError: __init__() missing 1 required positional argument: 'user'

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

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 168, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'user'```
#

Yeah change back to view = system(ctx.author)

#

That was correct

#

okay

slate swan
# slate swan Yeah change back to `view = system(ctx.author)`

now when i tap on the button it shows

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 224, in system
    await interaction.response.send_message(view=TicketView())
TypeError: __init__() missing 1 required positional argument: 'user'```
#

Oh yeah haven't seen

#

TicketView requires an argument

#

So like system(ctx.author)

#

ohhh

#

ill try

#

Just ctx.author won't work as ctx is not defined up there

#

yes

#

interaction

#

Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\Among Us IL Bot\main.py", line 224, in system
await interaction.response.send_message(view=TicketView(interaction.author))
AttributeError: 'Interaction' object has no attribute 'author'

hazy oxide
#

its interaction.user

slate swan
#

interaction.user

#

oh oops

#

author is implemented by some forks, dpy doesn't have it :p

#

tho author would make more sense imo ( since its an Union of Member and User)

#

how do i make it ephemeral

#

ephemeral=True when sending the message

#

oh okay

#

it all works

#

thank you all sm!

lost yoke
#

what error?

slate swan
#
await interaction.response.send_message(embed=embed,ephemeral=True)
        guild = interaction.guild
        category = discord.utils.get(guild.categories, name="Test")
        channeel = await guild.create_text_channel(f"etst-{interaction.user.name}", category=category, topic=f"test id/{interaction.user.name}")
       ``` any idea why it's not creating a text channel
(inside a button class)
rugged shadow
#

you can run it fine

lost yoke
#

Is there any way I can take it off?

slate swan
#

yes

lost yoke
#

how?

slate swan
#

right click on ur code and click on sort imports

#

it will change the order of your imports to the one following pep8

#

any idea guys?

lost yoke
#

thanks, work!

slate swan
#

add some print statment to verify

#

No need of print statement

#

If the embed doesn't get send, it most likely doesn't reach the code bravemmlol

#

it's not getting triggered

slate swan
#

slate swan
#

all other functions are getting triggered

#

first imports of stlib, then from imports of stdlib
then same for external libs

dull knot
#

Been awhile I've visited this server.
So, well. What I'm trying to do here is if the author reacts to the bot message (Sent after executing the cmd), it will send the respective embed. But this one doesn't work? Is there any alternative ways I can go about this? (This isn't the full code but yeah, it's basically what I'm trying to do)

if Ten in RandomBellResult:
            TenResponse = await ctx.send (embed=EmbedInput)
            await TenResponse.add_reaction("![BellMove](https://cdn.discordapp.com/emojis/1025832545222410270.webp?size=128 "BellMove")")
            if str(Reaction.is_custom_emoji) == "![BellMove](https://cdn.discordapp.com/emojis/1025832545222410270.webp?size=128 "BellMove")":
                await ctx.edit_message(Embed=TenEmbedOutput)
#

There are like multiple embeds for this. I'm making a command, similar to OwO's ,bell cmd

#

Like this

slate swan
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
dull knot
slate swan
#

check (Optional[Callable[…, bool]]) – A predicate to check what to wait for. The arguments must meet the parameters of the event being waited for.

dull knot
#

ALright. Noted will keep these in mind. Thanks! heartofroggo

slate swan
#

Why are you calling the command in the middle of an embed?

naive briar
#

job_list only takes 1 argument, you gave it 2

#

Just give it 1 argument? 🤨

slate swan
#

Remove the call to that command

naive briar
#

Idk what that function does or need

slate swan
#

You will run in an endless loop if you call it

#

You're calling the command again

#

Don't do it

#

As it will call the command over and over and run in an endless loop

#

Yes

#

Yeah, because your function to get the list of jobs should be named differently and called again

#

Not job_list

#

As that's the name of the function for your command

#

get_jobs_list might be good I suppose

#

Then you can call it like before with + await get_jobs_list(interaction, 1) if you have the same function arguments as you did before

bright wedge
slate swan
#

Nvm its ik

#

Ok

#

I'll go on my way home and then rest a bit, ask here and someone else may help otherwise I'll check out when I'll be back

bright wedge
#
  • you need to optimize your code
#

Theses get channel definitions and if elif statements is to much

dull knot
#

Section of code that got the error

        elif Hundred in RandomBellResult:
            HundredResponse = await inter.send (embed=EmbedInput)
            await HundredResponse.add_reaction("![BellMove](https://cdn.discordapp.com/emojis/1025832545222410270.webp?size=128 "BellMove")")
            
            def check(reaction, user):
                return user.id == inter.author.id and str(reaction.emoji) == "![BellMove](https://cdn.discordapp.com/emojis/1025832545222410270.webp?size=128 "BellMove")"

            try:
                reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)

            except asyncio.TimeoutError:
                await inter.send('👎')
            else:
                await inter.edit(Embed=TenEmbedOutput)

Error:

Ignoring exception in command bell:
Traceback (most recent call last):
  File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\Shuma\Desktop\Programming\VS Code\Neko-Nyan\Random\TestCmds.py", line 201, in Bell
    await inter.edit(Embed=TenEmbedOutput)
AttributeError: 'Context' object has no attribute 'edit'

The above exception was the direct cause of the following exception:
#
Traceback (most recent call last):
  File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\bot_base.py", line 578, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 914, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Shuma\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\disnake\ext\commands\core.py", line 181, in wrapped
    raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'edit'

What am I doing wrong here?

#

I'll probably be sleeping soon so ping me if replying

slate swan
#

how do you fetch a guild by it's id inside a button class?

#

interaction.get_guild doesn't work
nor does client.get_guild

naive briar
unkempt canyonBOT
slate swan
#

i want to fetch a specific guild

#

@

#

@naive briar

naive briar
slate swan
#

nope it doesn't

rare echo
slate swan
#

dpy.2.0

#

any help?

#
g = bot.get_guild(id) or await bot.fetch_guild(id)
robust fulcrum
#

Guys how can I make a !d command like @unkempt canyon in dpy?

slate swan
#

Go by yourself on the website, it doesn't exist (anymore)

slate swan
#

Look at the code and get inspiration, it's open source... (Read the bot's 'about me')

robust fulcrum
naive briar
#

Isn't after.roles and before.roles already returning Role object?

#

Why would you try get the role again

#

Just use the roles that the after return?

#

Do you really have to ask

slate swan
#
async def change_status(*args, **kwargs):
        guild = bot.get_guild(246691336776843265) 
        membercount = guild.member_count
        await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="{} members".format(membercount)))
        await sleep(10)
        await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type=discord.ActivityType.watching, name="Noazx#0001 Developer!"))
        
@bot.event
async def on_ready():
  change_status.start()```
im trying to make the status change and that doesnt work
#

my bot stopped working after the API update. What should i do?

finite salmon
#

Which API do you use? What errors do you get?

slate swan
#

OH NVM

finite salmon
glad cradle
#

he's using a loop in a weird way

slate swan
finite salmon
glad cradle
slate swan
#

i mean

#

it works but thank you sm anyways!

glad cradle
slate swan
finite salmon
# finite salmon Actually it's not

I'm going to use task.loops but for now I'm using a function which has that and I'm calling it on on_ready (ik that it's not a good practice)

glad cradle
#

!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 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.

glad cradle
#

you can't send an embed when defering an interaction

#

you need to first defer and then to edit the original response

#

your code is so messy

#

btw have you saved the changes?

#

also ctx is ctx and interaction is interaction, you shouldn't use ctx to represent an interaction, they works in different ways

#

look at your code lmao

primal token
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
primal token
#

I recommend you read the kwargs the method can accept

glad cradle
#

I mean look at your function, you're using ctx everywhere to represent an interaction object

slate swan
#

listen function is not working, there is some problem relating to intents

#

can someone help me out?

glad cradle
#

yea, what's your problem?

slate swan
#

listen function is not working, there is some problem relating to intents

glad cradle
#

which event you're listening

slate swan
#

default

hushed galleon
unkempt canyonBOT
#

examples/app_commands/slash_basic.py lines 20 to 23

@bot.slash_command(guild_ids=[...])  # Create a slash command
async def hello(ctx: discord.ApplicationContext):
    """Say hello to the bot"""  # The command description can be supplied as the docstring
    await ctx.respond(f"Hello {ctx.author}!")```
glad cradle
hushed galleon
#

i made the assumption of pycord based on the @slash_command decorator and the discord namespace in their traceback

hushed galleon
slate swan
#

how do i make my bot read messages after the intents update. I don't know what has happened after the update

#

!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 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.

slate swan
#

Enable the message_content intent, that's it

#

WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected. what do i do?

#

Exactly what is written above

#
  1. Enable the intent in code
  2. Enable the intent in developer portal
#

how do u enable it in code?

#

See above, for the third time

#

Still hasn't changed in-between

slate swan
#

One more person that cannot read, wonderful notlikethis

#

I believe I clearly wrote

message_content

#

so i wanna make an event that if member says something on a channel it deletes the message and turn it into an embed, how do i do that?

unkempt canyonBOT
#

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

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

Warning

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

oh yes thanks

livid jacinth
#

How can i create / cmds ? Can someone show me an example?

fading marlin
mighty pilot
#

is there a way to edit a regular message thats not a response

slate swan
#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

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

thanks

fluid haven
#

how to delete an ephemeral message in nextcord after an interaction with its view button?

fading marlin
#

Bots can't delete ephemerals iirc

slate swan
#

Exactly

fluid haven
#

ow

#

thats quite stupid but ok

slate swan
#

That's the purpose of ephemeral messages

#

Why

slate swan
fluid haven
#

u can't use .response multiple times

naive briar
#

Pretty sure you can't

slate swan
#

or can't?

fluid haven
#

can't sorry

slate swan
#

"Can't" most likely

#

so how can i change it?

naive briar
#

Use followup

fading marlin
# slate swan

but why... just check if rate is inside a list or something, all of those ifs look very messy and are pretty pointless if you're doing the same thing regardless of the value of rate notlikeduck

slate swan
livid jacinth
# fading marlin useful gist: <https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129...

But I cant start the bot. I dont get any error .

import discord
from discord import app_commands
from discord.ext import commands

class MyCog(commands.Cog):
  def __init__(self, bot: commands.Bot) -> None:
    self.bot = bot
    
  @app_commands.command(name="command-1")
  async def my_command(self, interaction: discord.Interaction) -> None:
    """ /command-1 """
    await interaction.response.send_message("Hello from command 1!", ephemeral=True)

  @app_commands.command(name="command-2")
  @app_commands.guilds(discord.Object(id=922642978940526653))
  async def my_private_command(self, interaction: discord.Interaction) -> None:
    """ /command-2 """
    await interaction.response.send_message("Hello from private command!", ephemeral=True)

async def setup(bot: commands.Bot) -> None:
  await bot.add_cog(MyCog("TOKEN"))
slate swan
#
        if rate == "2":
            await inter.response.send_message("Dziękujemy za opinię!", ephemeral = True)
            embed = disnake.Embed(title = "Opinia", description = f"{osoba} ({osoba2})\n\n:gwiazdka:\n\n{textValue}", color = 0x2f3136)
            embed.set_image(url = "https://cdn.discordapp.com/attachments/1018592616226496568/1020638078844555295/luckyTest.png")
            await inter.channel.send(embed = embed)
        if rate == "1":
            await inter.response.send_message("Dziękujemy za opinię!", ephemeral = True)
            embed = disnake.Embed(title = "Opinia", description = f"{osoba} ({osoba2})\n\n:half:\n\n{textValue}", color = 0x2f3136)
            embed.set_image(url = "https://cdn.discordapp.com/attachments/1018592616226496568/1020638078844555295/luckyTest.png")
            await inter.channel.send(embed = embed)
        else:
            await inter.response.send_message("Wpisałeś złą wartość! Pamiętaj, że ocena musi być w przedziale od 1-10", ephemeral = True)```
fading marlin
fading marlin
livid jacinth
slate swan
#

Bruh🤌

#

the same error

slate swan
#

Never seen that before 🤷🏾

glad cradle
#

lmao followup exist in disnake

slate swan
glad cradle
#

!d disnake.Interaction.followup

unkempt canyonBOT
winged coral
#

I think it would be pretty stupid if it didn't have it lol

slate swan
glad cradle
#

btw it's better to use inter.send as it automatically handle response or followup

fading marlin
stone quest
#

yo anyone know how to handle parameters from message content? its for a good reason not just a case that i dont know how to use commands

winged coral
#

Depends how you want them split

#

I assume it's more complex than just spaces?

slate swan
#

One that would interpret !say "Hello world" yes as 2 parameters

  • Hello world
  • yes
#

Otherwise make your own parser

fading marlin
#

shlex.split or commands.view.StringView (undocumented) would be good alternatives for that

slate swan
#

Oh shlex also exists on Python nice

stone quest
slate swan
#

Yeah then I recommend shlex as I use an implementation of that for my projects

#

Didn't know Python also had shlex

stone quest
#

i never knew about shlex, whats its overall usage?

fading marlin
#

🤷 I've only used it for string parsing

slate swan
#

Well string parsing

fading marlin
#

oh

stone quest
#

dope

slate swan
#

The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell. This will often be useful for writing minilanguages, (for example, in run control files for Python applications) or for parsing quoted strings.

TL;DR string parsing KEKW

#

Other, more understandable, description

A simple lexer which splits input in tokens using shell-style rules for quoting and commenting.

stone quest
#

ty

slate swan
#

shell lexer I suppose

#

Damn I'll sleep less stupid tonight pOg

stone quest
#

@fading marlin you are amazing - thanks.
['hello there', '123123', '132', '123', '123'] Pray

fading marlin
#

Anytime! rooDuck

stone quest
#

found it i think

fading marlin
#

You can use the * to unpack a list, e.g

some_list = [1, 2, 3, 4, 5]
def function(one: int, two: int, three: int, four: int, five: int) -> int:
    return sum((one, two, three, four, five))
function(*some_list)  # returns 15
stone quest
#

yeeeeeeeeee

#

thank you

fading marlin
#

No problem!

primal token
slate swan
#

yoikes good luck for that

primal token
#

Thanksducky_beer

slate swan
#

i'm not into that madman stuff

#

i let others have the headache

primal token
#

me neither, i just want to implement a language for experience and it's not going to be domain specific which makes the matter worse

slate swan
oblique totem
#

.

primal token
#

😔

vagrant tree
#

Guys does anyone know how to recreate this effect? With the dark outline around the text, and the green border?? I need a discord bot to send text that looks like this :P

fading marlin
#

Those are called embeds

#

!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...
vagrant tree
fading marlin
#

Sure thing

vagrant tree
#

:D

mighty pilot
#

Can I assign a role to someone with just the ID?

#

Tried await message.author.add_roles(role.id==12345...) but it says I still need a name

sick birch
#
await message.author.add_roles(discord.Object(id=12345))
mighty pilot
#

Ah alright. Thanks

sick birch
#

yup

lost yoke
#

`Traceback (most recent call last):
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 862, in _do_call
return await self.callback(interaction, **params) # type: ignore
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\comandos.py", line 94, in clear
await inter.response.send_message(embed=msg, ephemeral=True)
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\interactions.py", line 762, in send_message
await adapter.create_interaction_response(
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\webhook\async
.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "c:\Users\Acer\OneDrive\Documentos\Minhas pastas\Bot Geraldo\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File `

#

this log is from a clean chat code, it cleans but doesn't show the embed, what's wrong?

somber sky
#
@commands.has_permissions(administrator=True)
async def activity(ctx):
 msg = await ctx.send("**Activity Check**\n\n@everyone")
 await ctx.message.delete()
 await msg.add_reaction(':Check_Mark:')``` I haven't coded in months I am trying to re learn so yea
somber sky
#

nah

lost yoke
#

bruh

glad cradle