#discord-bots

1 messages · Page 926 of 1

desert badger
#
            try:
                voice_client = await voice_channel.connect()
                print(f"{Fore.BLUE}{dt_string}{Fore.RESET} Re-Connected to {Fore.MAGENTA}{voice_channel}")
            except:
                pass   

how can i change the try part to a function that checks if my bot is connected to a voice channel ? (saved my voice channel as voice_channel
like```py
if client is not connected to voice_channel:
connect

#

hope someone can help me :)

slate swan
#

ok

desert badger
#

ok

slate swan
#

ok

#

wwait

#
voice = disnake.utils.get(self.bot.voice_clients, guild=ctx.guild)
#

i return a bool

#

i use it

#

@desert badger

slate swan
#

?

#

it works fine

placid skiff
#

i literally told you .-.

hoary cargo
unkempt canyonBOT
slate swan
#

epic

#

🥲

desert badger
#

thx

fluid spindle
#

Are there any free services available to host bots?
I have been using Replit till now but the bot keeps going offline due to timeouts (even though I'm pinging a web server made for the bot using UptimeRobot).

spring flax
#

@fluid spindle ^

fluid spindle
spring flax
#

Considered self hosting then?

fluid spindle
#

I did. And I've realised it wouldn't work for me unless a buy a raspberry Pi.
Guess I'll have to stick with Replit then

spring flax
#

No PC?

fluid spindle
fluid spindle
spring flax
#

For REPLIT:

  • The machines are super underpowered.

    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.

    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.

    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

fluid spindle
#

Yup, I've read all this like 10 times now

spring flax
#

There is one more or less decent option imo..

fluid spindle
#

And I've other free options too, Replit suits my needs the best

spring flax
#

How big is the bot?

fluid spindle
#

Pretty small actually

spring flax
#

Like how many servers,

fluid spindle
#

Only for personal and friends' use

fluid spindle
spring flax
#

Okay well, free hosting servers are generally not good and errors like the one you're facing are expected to occur because they're not meant for hosting bots

fluid spindle
#

True

#

Though, it has been working fine for a year. The downtime problem started only 1 or 2 months ago

spring flax
#

I honestly don't know what to reference you to... i had an option in mind but it's not very ideal considering it's a personal bot only

robust fulcrum
#

Can anyone help how to make status changer for bot in python

fluid spindle
spring flax
#

if you are willing to do it, do you have a credit card?

spring flax
slate swan
#

status changer

robust fulcrum
#

Like many bot's status changes after 5 seconds

fluid spindle
robust fulcrum
#

And new status appear

spring flax
spring flax
slate swan
#

oracle prob

spring flax
robust fulcrum
boreal ravine
#

Does anyone know a free host that has ffmpeg

robust fulcrum
#

Maybe people use repl.it for hosting

slate swan
#

no

boreal ravine
#

it doesn't support ffmpeg anymore

fluid spindle
#

Lol

spring flax
#

i don't think that's allowed here <@&831776746206265384>

velvet compass
#

Yeah I'm gonna say its NSFW

#

Please don't post photos here to test in the future

south jetty
#
        with open("data.json") as f:
             data = json.load(f)
             
        guild = interaction.guild
        categ = discord.utils.get(guild.categories, name="Open Tickets")
        for ch in categ.text_channels:
            if ch.name == f"{interaction.user.name.lower()}":
                await interaction.response.send_message("You already have a ticket opened!", ephemeral=True)
                return ```
Can someone help me with this, How would I prevent someone from creating another ticket
spring flax
#

!d discord.ext.commands.Bot.change_presence

unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
south jetty
#

what do you mean stock the opened ticket on a file

spring flax
#

you should consider using a database if the bot is used by a lot of members

boreal ravine
south jetty
#

because the numbers changes

boreal ravine
south jetty
#

so it will register the tickets id

south jetty
boreal ravine
south jetty
south jetty
boreal ravine
#

yea

south jetty
#

didn't work

boreal ravine
south jetty
boreal ravine
#

you're supposed to say no if theres no error

south jetty
#

oh no

boreal ravine
#

well do what name said

south jetty
#

i don't know how to store the users id

boreal ravine
#

bad way:
store the users id in a json file, then when the user tries to create a ticket check if the user is in the json file
good way:
like the above, but using a database

south jetty
#

database?

boreal ravine
#
if ch.name.startswith('bedrockedition'):
    ...
south jetty
#

ok

boreal ravine
#

oh well if you have any more issues ping me

#

i'm gonna go play minecraft Vibe

south jetty
#

alright

boreal ravine
#

hey sparky

slate swan
#

components must be a WrappedComponent, a list of ActionRow or a list of WrappedComponent

#

@slate swan

#

@boreal ravine

slate swan
#

Ignoring exception in command ticketchannel:
Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\core.py", line 169, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\hp\Desktop\bot\save.py", line 44, in ticket
await channel.send(embed=embed2,components=RowButtons)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\abc.py", line
1475, in send
components_payload = components_to_dict(components)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ui\action_row.py", line 312, in components_to_dict
return [row.to_component_dict() for row in components_to_rows(components)]
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ui\action_row.py", line 300, in components_to_rows
raise ValueError(
ValueError: components must be a WrappedComponent, a list of ActionRow or a list of WrappedComponent

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

Traceback (most recent call last):
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\bot_base.py", line 570, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\core.py", line 920, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\commands\core.py", line 178, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: components must be a WrappedComponent, a list of ActionRow or a list of WrappedComponent

boreal ravine
#

uhm

#

im not good with disnake sorry sad_cat

slate swan
#

its same huh?

#

ik what i have did wrong

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

its error?

#

error in py extension?

#
class RowButtons(disnake.ui.View):
     def __init__(self):
        super().__init__(timeout=None)
     @disnake.ui.button(label="Create ticket", style=ButtonStyle.blurple)
     async def first_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        guild_id = str(interaction.guild.id)
        if guild_id in logss.keys():
         logsid = logss[guild_id]
         channelslogs = self.bot.get_channel(logsid)
         category = channelslogs.category
         await channelslogs.guild.create_text_channel(name="ticket", category=category , overwrites=overwrite2)
#

it is in different file

#

and

slate swan
#
await channel.send(embed=embed2,components=RowButtons)
boreal ravine
slate swan
#

alright

spring flax
slate swan
#

view =

slate swan
spring flax
#

!d disnake.abc.Messageable.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://docs.disnake.dev/en/latest/api.html#disnake.File "disnake.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed "disnake.Embed") objects. **Specifying both parameters will lead to an exception**.
spring flax
#

view (ui.View) – A Discord UI View to add to the message. This cannot be mixed with components. New in version 2.0.

slate swan
slate swan
#

i forgot to add

#

also

#

how to get a class from a class!?!?

#

how to import*

placid skiff
boreal ravine
slate swan
#
class ticket(commands.Cog):
    """huh4?."""
    def __init__(self , bot: commands.Bot):
        self.bot = bot 
    class RowButtons(disnake.ui.View):
     def __init__(self):
        super().__init__(timeout=None)
     @disnake.ui.button(label="Create ticket", style=ButtonStyle.blurple)
     async def first_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        guild_id = str(interaction.guild.id)
        if guild_id in logss.keys():
         logsid = logss[guild_id]
         channelslogs = self.bot.get_channel(logsid)
         category = channelslogs.category
         await channelslogs.guild.create_text_channel(name="ticket", category=category , overwrites=overwrite2)
#

i aslo want self.bot

boreal ravine
#

bruh

#

move it outside the class

slate swan
#

..

slate swan
#

he means not to nest classes

boreal ravine
slate swan
#

and you dont need to nest the classes

#

ok

#

example pls?

#

when you add a view you add an instance of the class so no need for it

#

yse

#
class RowButtons(disnake.ui.View):
     def __init__(self , bot: commands.bot):
         self.bot = bot
         super().__init__(timeout=None)
``` lke this?
#

no

#

then

#

view doesnt need any arguments

#

!d discord.ui.View

unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
slate swan
#

only timeout which you already passed it

#

?

#

i cant understand

#

what u are trying to say

#

idk what kayle ment

#

in rowbuttons class i want the bot

slate swan
#

just pass the bot???

slate swan
boreal ravine
slate swan
#

bro you just did

slate swan
quaint epoch
#

so i created a custom check - ```py
def can_close_tickets(self, ctx):
async def predicate(ctx):
try:
self.roles[ctx.guild.id]
except KeyError:
if ctx.author.guild_permissions.moderate_members:
return True
else:
return False
else:
for role in self.roles[ctx.guild.id]:
try:
if ctx.guild.get_role(role) in ctx.author.roles:
return True
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
print(f'Could not find role {role} in guild {ctx.guild.id} for ticket viewing.')
return False

    return commands.check(predicate)``` how do i apply this to a command?
slate swan
slate swan
#

its commands.Bot

#

its a class

#

ok that

quaint epoch
slate swan
quaint epoch
#

thanks

boreal ravine
#

I prefer to put it above commands.command tho

slate swan
slate swan
slate swan
#

i added that in dc*

#

excuse me?

#

ill fix it

#

alright

#

thanks

#
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: __init__()
missing 1 required positional argument: 'bot'
#

you need to pass the bot argument

#
class RowButtons(disnake.ui.View):
     def __init__(self , bot: commands.Bot):
         self.bot = bot
slate swan
#

thats causing error

#
await ctx.send(embed=embed, view=View(bot_instance))
#

when you subclass it, just pass the bot

#

😐

#

yes that

placid skiff
#

when you create the instance of the view you are not passing the bot object

slate swan
#

then when do you pass it GWcmeisterPeepoShrug thats how python works

boreal ravine
slate swan
#

in his case he does

placid skiff
#

maybe he literally wrote "bot_instance" D_D

slate swan
#

💀

#

?

#

because you do pass your bot instance

#

in his case*

#

and it was an example idk how his Bot instance is named

#

idk what to do

#

bro

#

..

#

we literally gave you a step by step how do you not understand

boreal ravine
slate swan
#

im gonna go spoonfeeding mode

cloud dawn
manic wing
slate swan
#

im just saying learning oop is helpful

#

¯\_(ツ)_/¯

quaint epoch
#

guys my custom check isn't working

placid skiff
#

code

cloud dawn
#

@slate swan View isn't the same as a Cog, in this case bot still needs to be passed.

quaint epoch
#

commands: py @commands.command(aliases=['cancel_ticket']) @can_close_tickets() async def close_ticket(self, ctx, channel: discord.TextChannel): if channel.name.startswith('ticket-'): async for entry in ctx.guild.audit_logs(limit=None, action=discord.AuditLogAction.channel_create, user=ctx.guild.me): if entry.target == channel: await channel.delete() return await ctx.message.reply(f'`{channel.name}` closed.') await ctx.send(f'Invalid channel.') await ctx.send(f'Invalid channel.')
Check:

    def can_close_tickets(self, ctx):
        async def predicate(ctx):
            try:
                self.roles[ctx.guild.id]
            except KeyError:
                if ctx.author.guild_permissions.moderate_members:
                    return True
                else:
                    return False
            else:
                for role in self.roles[ctx.guild.id]:
                    try:
                        if ctx.guild.get_role(role) in ctx.author.roles:
                            return True
                        if ctx.author.guild_permissions.moderate_members:
                            return True
                    except (discord.NotFound, discord.Forbidden, discord.HTTPException):
                        print(f'Could not find role {role} in guild {ctx.guild.id} for ticket viewing.')
                return False

        return commands.check(predicate)```
#

it says self and ctx aren't defined

placid skiff
#

why are you using self? do you declared it inside a cog?

quaint epoch
#

self.roles is a dict that commands in the cog use

placid skiff
#

not suggested to
it is better to take checks from themself

quaint epoch
#

what?

placid skiff
#

i usually create a folder called checks where i put my check.py script

quaint epoch
#

alr, but is there anyway to fix the error I'm getting?

placid skiff
#

probably not
can_close_tickets is a decorator so it is not supposed to take any argument, the argument you will pass in it will be argument that you will pass in the decorator. to make an example the has_permissions decorator in the source code is something like this:

def has_permissions(**perms: bool) -> Callable[[T], T]:
    invalid = set(perms) - set(disnake.Permissions.VALID_FLAGS)
    if invalid:
        raise TypeError(f"Invalid permission(s): {', '.join(invalid)}")

    def predicate(ctx: AnyContext) -> bool:
        ch = ctx.channel
        permissions = ch.permissions_for(ctx.author)  # type: ignore

        missing = [perm for perm, value in perms.items() if getattr(permissions, perm) != value]

        if not missing:
            return True

        raise MissingPermissions(missing)

    return check(predicate)
#

the **perms is a kwargs, the one you pass it in the decorator, like @has_permissions(administrator=True) (administrator is the kwargs

#

so essentially you are passing values in the decorator without passing them, and you cannot pass neither self and ctx in the decorator

#

a classic custom check should look like this:

class callError(CheckFailure):
    def __init__(self, message, bando: str):
        self.message = message
        super().__init__(message=message)

def is_call_active()->Callable[[T], T]:
    def predicate(ctx: AnyContext)->bool:
        if path.isfile(f"{PICKLE_DIR}/{ctx.application_command.qualified_name.split()[1]}"):
            bando: Bando = pickle.load(f"{PICKLE_DIR}/{ctx.application_command.qualified_name.split()[1]}")
            if bando.is_active:
                return True
            else:
                raise callError(message="This call is inactive", bando=bando.name)
        else:
            raise callError(message="There is no call with that name", bando=ctx.application_command.qualified_name.split()[1])
    return check(predicate)
spring flax
maiden fable
#

What

spring flax
# maiden fable What

it was a line in the has_permissions deco source above. I just checked the docs and saw it is AnyContext = Union[Context, ApplicationCommandInteraction] but I thought it was part of a module nevermind

slim whale
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

placid skiff
# spring flax Can you give the docs on anycontext?

is usefull when you use a package which has both application commands and bot:

from type import Union
from disnake import ApplicationCommandInteraction
from disnake.ext.commands import Context

AnyContext = Union[Context, ApplicationCommandInteraction]
``` this is for disnake for example
spring flax
#

also what exactly are type checkers?

placid skiff
#

what checkers?

#

do you mean type hints?

#

like ctx: Context

spring flax
spring flax
#

(i pinged him because he knows what i'm talking about)

maiden fable
# spring flax also what exactly are type checkers?

More of a question for #type-hinting but they are the modules which see if u r passing in the correct datatype

def func(a: int):
    print(a)

So this function has an arg a which is expecting an int type but if u pass in "a", the type checkers will show a warning with a Yellow line or smth (as configured in yr IDE)

spring flax
#

so how does #type ignore ignore it?

placid skiff
#

is used when you want to ignore error code in square brackets, something like this:

x: int
x: str

raises:

error: Name 'x' already defined on line 1 [no-redef]

if you do this:

x: int
x: str #type: ignore [no-redef]

you will not have the error in output

maiden fable
spring flax
#

that's cool, is that in-built behaviour?

maiden fable
#

Yea

cloud dawn
#

Don't recommend doing it though.

maiden fable
#

Yup

placid skiff
#

is useless too xD

spring flax
#

yeah I just saw it in a lot of code and wanted to know what it was

cloud dawn
#

Also Pycharm can automatically create these and for some errors i would use them.

placid skiff
cloud dawn
placid skiff
#

I use pycharm D_D

cloud dawn
#

But i would only use it for bigger Python projects.

spring flax
#

what's gut?

cloud dawn
#

good*

maiden fable
#

Nvm yea, just read the context

placid skiff
#

git lol

spring flax
#

is pycharm better than VScode?

cloud dawn
cloud dawn
spring flax
placid skiff
#

PyCharm is optimized for python, VSCode is something between a text editor and an IDE, that can be used to create project for more languages, but intellisense works differently

cloud dawn
#

Pycharm aside from Python also has web-building build in. Stuff for js, html, css and templates for Flask or Django.

maiden fable
#

(get good)

formal basin
#

I don’t understand why it’s giving me this error

quick gust
#

on_message takes a message arg and your ctx is a message object and not a context object

#

you can do message.channel.send instead

quick gust
#

and it'll be better if u rename the ctx arg to message, ctx is confusing in on_message

formal basin
#

Ok

#

Did it I’m going to test it

#

It works

slate swan
#
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
    base.commit()
    print(1)

    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if reason is None:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
       base.commit()
       print(2222)
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
       await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
    else:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
       base.commit() 
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
        await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")    

not working. Nothing output excepting 45 and 1, why?

maiden fable
#

Didn't ask the same question yesterday too? Idk

tidal hawk
#

He asked it like 3 days ago

regal cove
#

why does this piece of code block my whole bot from working?

this is my code:

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  if not message.guild:
    try:
      embed = discord.Embed(title="Why dm a bot?", description="Hello, i dont know why you thought it was a good idea to dm a bot that has no feelings and cant answer you. If u had a question about my service please dm: Selon#7182 \n\n so in conclusion dont dm me bro im just a bunch of ones and zeros",
                              color=0xae4dff)
      await message.channel.send(embed=embed)
    except discord.errors.Forbidden:
      pass
  else:
    pass
slate swan
#

!d discord.ext.commands.Bot.listen

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/master/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...
tough lance
#

Or use process_commands

#

If you're using commands.Bot

slate swan
#

just use listen it will save a line and you dont need to process all on message events

regal cove
#

so this should work?

@listen(name=None)
async def on_message(message):
  if message.author == client.user:
    return
  if not message.guild:
    try:
      embed = discord.Embed(title="Why dm a bot?", description="Hello, i dont know why you thought it was a good idea to dm a bot that has no feelings and cant answer you. If u had a question about my service please dm: Selon#7182 \n\n so in conclusion dont dm me bro im just a bunch of ones and zeros",
                              color=0xae4dff)
      await message.channel.send(embed=embed)
    except discord.errors.Forbidden:
      pass
  else:
    pass```
slate swan
#
@client.listen()

if client is an instance of Bot

regal cove
#

ok

slate swan
#

as Astrid said

tough lance
#

I think cuz commands are available in commands.bot and not in client

regal cove
#

i fixed it

#

and it works now

slate swan
#

lol

tired agate
#
async def node_connect():
    await bot.wait_until_ready()
    await wavelink.Nodepool.create_node(bot=bot, host='lavalinkinc.ml', port=443, password='incognito', https=True)

i get this:

AttributeError: module 'wavelink' has no attribute 'Nodepool'

pls help me idfk what im doing 🙏

slate swan
#

well the module doesnt have that attribute

#

!e print(import("os").copy())

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | AttributeError: module 'os' has no attribute 'copy'
tired agate
#

🤷‍♂️

tired agate
manic wing
tough lance
tired agate
tough lance
#

Oh I get it

#

It's wavelink.NodePool @tired agate

tired agate
#

tysm !

fathom scroll
#

hi, im new on discord.py and i want to make on_message event but it trigger only if the message is DM code:

@client.event async def on_message(message): //stuff

fathom scroll
# spring flax What's the //stuff?

if ctx.author.id == 853316867544449025: if len(ctx.content) == 17: channel = client.get_channel(932302059888341064) await channel.send(ctx.content)

#

no errors and nothing sending

narrow rune
#

if not message.guild

#

but using ctx on on_message dont make sense

fathom scroll
#

i can replace all the ctx with message but still nothing

narrow rune
#

or u could do if message.channel.type == 'private'

fathom scroll
#

i want to make it in guild chat, like when someone with specified id type something it will trigger but that code i send work only if i send dm message to bot

hoary cargo
cold sonnet
#

or just replace message with ctx

#

with false naming

fathom scroll
#

yea i does that

#

still nothing

cold sonnet
#

show code

#

more

#

or is that all

#

is the bot online? 👀

tired agate
#
@bot.command()
async def play(ctx,*, search: wavelink.YouTubeTrack):
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    elif not ctx.author.voice():
        return await ctx.send("Join a VC kid !")
    else:
        vc : wavelink.Player= ctx.voice_client
    await vc.play(search)

i get this error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'VoiceState' object is not callable

idfk what im doing pls help

dire folio
#

I'm pretty sure this server isn't supposed to help with this kind of stuff

slate swan
#

!yt_dl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
#

how can i make this send into the channel that i mention in the commands?

@client.command()
@commands.has_permissions(administrator=True)
async def say(channel: discord.TextChannel, message):
    await channel.send(f"{message}")

whenever I do !say #channel test it won't work

sick birch
#

We can’t help with playing YouTube videos on discord, sorry

slate swan
#

ohh okay

#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
slate swan
slate swan
#

make the message argument a kwarg

#

or it will only expect one word which gets passed in the positional argument

halcyon sparrow
#

jam_cavedude I can't belive my error handler worked

tired agate
boreal ravine
#

ok

tired agate
#
@bot.command()
async def play(ctx,*, search: wavelink.YouTubeTrack):
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    elif not ctx.author.voice:
        return await ctx.send("Join a VC kid !")
    else:
        vc : wavelink.Player= ctx.voice_client
    await vc.play(search)

i get this error:

TypeError: source must an AudioSource not YouTubeTrack

idfk wavelink someone pls help me 🙏

toxic bluff
#

Anybody knows if its possible to archive am active Thread with a Bot (the Bot also creates the Thread). I'am using the disnake library. I didn't find any method supporting it in the disnake.Thread class

vale sierra
#
@bot.event
async def on_raw_reaction_add(payload):
    global category
    if payload.member.id != bot.user.id and str(payload.emoji) == u"\U0001F3AB":
        msg_id, channel_id, category_id = bot.ticket_configs[payload.guild_id]

        if payload.message_id == msg_id:
            guild = bot.get_guild(payload.guild_id)

            for category in guild.categories:
                if category.id == category_id:
                    break

            channel = guild.get_channel(channel_id)

            ticket_channel = await category.create_text_channel(f"ticket-{payload.member.display_name}",
                                                                topic=f"Channel pour {payload.member.display_name}.",
                                                                permission_synced=True)
            overwrites = {
                guild.default_role: discord.PermissionOverwrite(read_messages=False),
                guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True),
            }

            message = await channel.fetch_message(msg_id)
            await message.remove_reaction(payload.emoji, payload.member)

            await ticket_channel.send(
                f"> {payload.member.mention} Merci d'avoir créer un ticket ! Si vous voulez fermez ce channel, utilisez **'-close'**.")

            try:
                await bot.wait_for("message", check=lambda
                    m: m.channel == ticket_channel and m.author == payload.member and m.content == "-close",
                                   timeout=3600)

            except asyncio.TimeoutError:
                await ticket_channel.delete()

            else:
                await ticket_channel.delete()
``` hello, i have this error with this code, note that the key error = serverid !
boreal ravine
boreal ravine
tired agate
#

im sorry

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | KeyError: 3
slate swan
#

the key isnt correct

north peak
#

How can I get users discord join date and convert it to unix timestamp

this I have rn is not working

date = str(member.created_at.strftime("%#d/%B/%Y/%I/%M"))
unixdate = int(datetime.datetime.strptime(date, '%d/%m/%Y/%M/%S').strftime("%s"))
boreal ravine
unkempt canyonBOT
#

await edit(*, name=..., archived=..., locked=..., invitable=..., slowmode_delay=..., auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the thread.

Editing the thread requires [`Permissions.manage_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_threads "disnake.Permissions.manage_threads"). The thread creator can also edit `name`, `archived` or `auto_archive_duration`. Note that if the thread is locked then only those with [`Permissions.manage_threads`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.manage_threads "disnake.Permissions.manage_threads") can unarchive a thread.

The thread must be unarchived to be edited.
echo wasp
#

how do i set the footer of a embed message to have the timestamp?

slate swan
unkempt canyonBOT
#

The timestamp of the embed content. This is an aware datetime. If a naive datetime is passed, it is converted to an aware datetime with the local timezone.

boreal ravine
boreal ravine
boreal ravine
boreal ravine
#

👍

north peak
boreal ravine
echo wasp
#
        em = discord.Embed(title=f'Welcome {member}' description=f"Hey, {member.mention} Welcome to {member.guild}! \n Please read the rules in [#925976154890993734](/guild/267624335836053506/channel/925976154890993734/) \n You can get support for my bot in [#904216450707881994](/guild/267624335836053506/channel/904216450707881994/) \n Please enjoy your stay!")
        em.set_thumbnail(url=member.avatar.url)
        em.set_footer(timestamp)
        await channel.send(embed=em)``` this is giving invaild syntax why
boreal ravine
echo wasp
slate swan
#

it just points out at where the error ends

echo wasp
slate swan
#

or somewhere else it just never finds the error exactly as some stuff are literal blah blah blah

boreal ravine
slate swan
echo wasp
honest shoal
#

how can I have the mobile online status on my bot?

slate swan
#

timestamp=datetime.datetime.now()

echo wasp
#

thank you

boreal ravine
honest shoal
#

just want to try, I don't want it permamnently

boreal ravine
#

right

#

do ?tag real mobile status in the d.py server

honest shoal
#

ohh..

left crater
#

how can i check if a user has his dms off?

delicate hornet
#

why are all roles at postion 1?
there was code!

delicate hornet
left crater
#

is that the only way?

boreal ravine
#

yes

left crater
#

ok

boreal ravine
slate swan
delicate hornet
sick birch
unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

sick birch
#

Don’t think that’s a thing

boreal ravine
#

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

boreal ravine
sick birch
#

Discord doesn’t let you know ahead of time if someone has their DMs off

delicate hornet
slate swan
maiden fable
#

Uhhhh

boreal ravine
maiden fable
#

👀

slate swan
maiden fable
#

Nope

#

Lmao the method is weird

boreal ravine
unkempt canyonBOT
#

discord/abc.py line 1547

def can_send(self, *objects) -> bool:```
boreal ravine
#

thanks

slate swan
# maiden fable Nope

I remember when I got very confused for d.py getting shutdown, you then told me to use some fork you were creating, thought it was pycord.

maiden fable
#

Ah, disnake

#

Well I don't code discord bots anymore, but still prefer disnake cz they release features faster 😄

delicate hornet
slate swan
#

!d discord.Role.position

unkempt canyonBOT
#

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

slate swan
#

The position of the role. 🤷‍♂️

vale sierra
delicate hornet
slate swan
abstract kindle
#

would there be code I can write to have the bot show me where the instance is running from?

#

Cause I'm working on 2 computers and I close down the program on one of them, but there are still 2 instances

slate swan
abstract kindle
#

I see

slate swan
#

!d os.path

unkempt canyonBOT
#

Source code: Lib/posixpath.py (for POSIX) and Lib/ntpath.py (for Windows NT).

This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings. Unfortunately, some file names may not be representable as strings on Unix, so applications that need to support arbitrary file names on Unix should use bytes objects to represent path names. Vice versa, using bytes objects cannot represent all file names on Windows (in the standard mbcs encoding), hence Windows applications should use string objects to access all files.

sick birch
#

Read the documentation, ask for help, and read the examples on GitHub

#

Also work on lots of projects to hone your skills

slate swan
#

Hello guys

#

Can you help me to find some information about Twitter bots

abstract kindle
#

curious. If I'm making an economy bot that uses games to make money, would it be better to store each separate game and its code in a different cog, or all games in one cog

hoary solstice
#

Quick and rather simple question: if I want to deploy a bot, do I need to serve it? Like where does it "live"? If I test locally, I run it on my machine. If I want to run it on servers, I need to serve it somewhere, right?

abstract kindle
#

What do you mean serve it?

#

If you're using a hosting service, they basically take the deploy key for your bot and run it 24/7 on a computer somewhere else.

#

Servers would be like running your code on your machine and leaving it on 24/7

slate swan
#

hi uhm i made some code

slate swan
#

!resources | Hetr you can find different examples.

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.

echo wasp
#

how do you get a guild? like guild = self.client.get_guild(guild_id)

unkempt canyonBOT
#
No way, José.

No documentation found for the requested symbol.

slate swan
#

i made a quick bot to notify everyone when something rare spawns for another bot and when it notifies it spams it over and over

CODE:

@bot.event
async def on_message(message):
  if "raider" or "raid" or "dynamax" or "Multibattle" or "**BREAK**" or "**rare**" in message.content and message.channel.id == "903028441102827540":
    await message.channel.send("@everyone something spawned here lol. go check")```
echo wasp
slate swan
unkempt canyonBOT
#

await fetch_guild(guild_id, /, *, with_counts=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") from an ID.

Note

Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").

Note

This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.get_guild "discord.Client.get_guild") instead...
echo wasp
#

close

slate swan
#

heya

slate swan
abstract kindle
slate swan
#

Check the docs

hoary solstice
slate swan
abstract kindle
#

I would say put all the words you're looking for in a list and say if any of the words in the list are in the message

slate swan
#

it sends the msg but like

#

it spams it a bunch

slate swan
#

i only need it once

abstract kindle
#

I know

slate swan
unkempt canyonBOT
#

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

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

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

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

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

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

Because all of the or operators are accepting any message that comes through

slate swan
#

oh

#

brb den

#

Search for Webhook or something

abstract kindle
#

I'm not sure why it does that but I've had that problem

#

So put all the words in a list instead

knotty basin
#

Hey, i've been trying to create a Slash command group using discord.commands.SlashCommandGroup in a cog but I get this error

Traceback (most recent call last):
  File "C:\Users\milot\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 113, in wrapped
    ret = await coro(arg)
  File "C:\Users\milot\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 773, in _invoke
    await self.callback(ctx, **kwargs)
TypeError: activities._w2g() missing 1 required positional argument: 'ctx'
abstract kindle
#

Code please?

red wraith
#

Anyone interested in Quantum Computing or Technological Art???

echo wasp
#

how would i create a check like if ctx.author has role in guild ?

knotty basin
abstract kindle
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/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/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
echo wasp
abstract kindle
#

uhm, not sure how you would check in another guild

#

if using ctx, you can only check in that guild

slate swan
#

!d discord.Client.fetch_webhook

unkempt canyonBOT
#

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

Retrieves a [`Webhook`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook "discord.Webhook") with the specified ID.

Changed in version 2.0: `webhook_id` parameter is now positional-only.
echo wasp
abstract kindle
#

probably something with permissions then

slate swan
#

It returns NotFound if not found.

abstract kindle
#

are the devs admins in those other servers? @echo wasp

slate swan
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
abstract kindle
#

Does that display a list of every role for every server?

#

Or just the server theyre in

slate swan
#

The server they are in

abstract kindle
#

They're trying to check to see if members have roles across multiple different servers, which wouldn't work unless the Dev team's roles were all named exactly the same

slate swan
echo wasp
abstract kindle
#

Then you'd have to get the ID for every bot dev role in every server

slate swan
#

Yes

abstract kindle
#

And put them in a list and check and see if the user has any of those roles

#

Might be difficult to coordinate if your bot is big

echo wasp
#

here is an example lets say i need to run the %reload command in this server that my bot is in i have a single role in this server and i want to check if i have the dev role in my support server if i do work the command if i don't just return

abstract kindle
#

do you have code for it? or are you asking for some

echo wasp
abstract kindle
#

Ah I see. You want to see if you have a role in another server, and if you do, run the command in the first server?

echo wasp
#

yes

abstract kindle
#

not sure how you would check if a member has a role in another guild

#

give me a sec, I have to relocate real quick, class is done.

echo wasp
#

ok

trail dove
#

Hello, my discord bot won't join the VC. How to fix it?

final iron
#

voice_state doesn't exist?

#

It wasn't a question?

tired agate
#
@bot.command()
async def disconnect(ctx:commands.Context):
    if not ctx.voice_client:
        return await ctx.send("Pweasee let me join a VC <3")
    elif not ctx.author.voice:
        return await ctx.send("Pweasee join a VC <3")
    elif not ctx.author.voice == ctx.me.voice:
        return await ctx.send("Pwease be in the same VC <3")
    else:
        vc: wavelink.Player = ctx.voice_client
    await vc.disconnect()
    await ctx.send("The bot disconnected :( ") 

What error happens:

It triggers the condition of not being in the same VC, while I am in the same VC
echo wasp
trail dove
#

wharet

echo wasp
#

instead of not?

tired agate
#
@bot.event
async def on_wavelink_track_end(player:wavelink.Player, track: wavelink.Track, reason):
    ctx = player.ctx
    vc : player = ctx.voice_client
    
    if vc.loop:
        return await vc.play(track)
    next_song= vc.queue.get()
    await vc.play(next_song)
    await ctx.send(f"Playing: {next_song.title} rn :)")
@bot.command()
async def play(ctx: commands.Context,*, search: wavelink.YouTubeTrack):
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(cls=wavelink.Player)
    elif not ctx.author.voice:
        return await ctx.send("Pweasee join a VC <3")
    elif not ctx.author.voice != ctx.me.voice:
        return await ctx.send("Pwease be in the same VC <3")
    else:
        vc : wavelink.Player= ctx.voice_client
    if vc.queue.is_empty and vc.is_playing:
        await vc.play(search)
        await ctx.send(f"Playing: {search.title} rn :)")
    else:
        await vc.queue.put_wait(search)
        await ctx.send(f"Added {search.title} to the queue <3")
    vc.ctx = ctx
    setattr(vc,"loop",False)

i get this error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceClient' object has no attribute 'queue'

😢

manic wing
#

ctx.voice_client doesnt return a wavelink.PLayer instance

maiden fable
#

😔 We don't help with music bots, sorry

slate swan
#

😭

#

Wait

#

Nvm

tired agate
#
  em = discord.Embed("The queue <3",color=discord.Color.red())
    for song in queue:
        song_count += 1
        em.add_field(name=f"Number in Queue: {song_count}", value=f"`{song.title}`")
  return await ctx.send(embed=em)

I get this error:

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() takes 1 positional argument but 2 were given
maiden fable
#

title=

spring cape
#

Can I create a async def command inside a bot.event()?

maiden fable
#

No

#

Why would u want to tho

spring cape
#

Well I'm making a ticket system and want to restrict my delete command to a specific role, afaik I cannot check that unless I make it a command with async def.

#

Unless you maybe have a suggestion on how I should approach this @maiden fable

sick birch
#

There’s a has_role decorator

maiden fable
#

Well

sick birch
#

The pitfalls of mobile

maiden fable
#

Lmao

spring cape
sick birch
#

Outside what?

#

Your command?

spring cape
#

Yes for example in an If statement. Sorry if I'm asking dumb questions but I'm very new to discord bot dev.

sick birch
#

No dumb questions. You’d use the has_role decorator right above your command function, so yes outside

spring cape
#

Okay, thank you very much!

sick birch
#

My pleasure. Ping me if you need further assistance

spring cape
#

Sure thing.

tardy atlas
#
@bot.command()
async def пред(ctx, member: discord.Member = None, *, reason = None):
    print(45)
    cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild BIGINT, userid BIGINT, warn INT, count INT, reasons VARCHAR);""")
    base.commit()
    print(1)

    if member is None:
        await ctx.send("Выберите участника")
        return
        
    if reason is None:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,'Отсутствует'))
       base.commit()
       print(2222)
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
       await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина ``Отсутствует``.")
    else:
       cursor.execute('INSERT INTO warning(guild, userid, warn, count, reasons) VALUES(%s, %s, %s, %s, %s)', (ctx.guild.id,ctx.author.id,1,1,reason))
       base.commit() 
       cursor.execute('UPDATE warning SET warn = warn + 1 WHERE userid = %s AND guild = %s', (member.id, ctx.guild.id))
       base.commit()
        await ctx.send(f"**{member}** Выдал предупреждение {ctx.author.name} , причина {reason}.")     

not working. Nothing output excepting 45 and 1, why?

echo wasp
#

how would i create a customiable prefix for my discord bot?

slim ibex
#

Use a database

#

to store a prefix for each guild

#

and you can use when_mentioned_or in a prefix handler function to grab the prefix from the database for the message’s guild

#

it’s literally a two line function you have to write

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'

#

how to fix?

slim ibex
#

The query to get the prefix from the db and implementing when_mentioned_or

echo wasp
slim ibex
#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
slim ibex
slim ibex
#

How do you define your member

slate swan
slim ibex
#

Syntax error

#

Remove the = after description

#

And description is a kwarg for discord.Embed

#

So is color

#

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

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
slate swan
slim ibex
#

I don’t spoon feed

slate swan
#
async def suggestt(ctx, *, content:str): 
 channel = bot.get_channel(947973903060443206)
 await ctx.message.delete()
 echoembed = discord.Embed(title="Suggestion!")
 echoembed.set_author(name = ctx.author.display_name, icon_url = ctx.author.avatar_url)
 echoembed.description=(content)
 colour=discord.Colour.orange()
 await ctx.send(embed=echoembed)```
slim ibex
#

you will have to use what I gave you to carry on

slate swan
echo wasp
slim ibex
#

Before you can fix the actual error, you need to fix the syntax errors and clean the code up

slim ibex
echo wasp
echo wasp
slim ibex
#

make a custom prefix helper function and you can set command_prefix to the functions name

echo wasp
slim ibex
#

You need to write a query to grab the prefix based on the guild of the message sent

#

And return a call to when_mentioned_or

echo wasp
terse blade
#
async def on_member_join(member: disnake.Member):
  await bot.add_roles(member, 953020268656353350)``` dosent work why?
final iron
#

It's

#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
terse blade
#

still dont work

final iron
#

Saying it doesn't work doesn't help anyone

terse blade
#

well it dosent?

next heath
#

Hi Im geting a problem idk how to get a random images code:

@client.command()
async def (ctx, member: discord.Member = None):
    print("Now")
    guild = member.guild
   
    Image = {
           "image1": "./data/image1.png",
           "image2": "./data/image2.png",
           "image3": "./data/image3.png",
           "image4": "./data/image4.png",
           "image5": "./data/image5.png",
           "image6": "./data/image6.png",
           "image7": "./data/image7.png",
           "image8": "./data/image8.png",
           "image9": "./data/image9.png",
           "image10": "./data/image10.png",
           "image11": "./data/image11.png",
           "image12": "./data/image12.png",
           "image13": "./data/image13.png"
           }

    Image2 = Image.open(random.choice(list(Image.keys())))

    font = ImageFont.truetype("./data/Royalacid.ttf", 75)
    font2 = ImageFont.truetype("./data/OpenSans-Semibold.ttf", 30)
    
    text = f"Welcome, {ctx.author.name}"
    text2 = f"Members: {ctx.author.member_count}"
    
    asset = ctx.author.avatar_url_as(size = 128)
    data = BytesIO(await asset.read())
    draw = ImageDraw.Draw(Image2)
    pfp = Image.open(data)
    
    pfp = pfp.resize((207,203))
    draw.text((16,600), text, (0, 255, 242), font)
    draw.text((11,1), text2, (0, 255, 242), font2)
    Image2.paste(pfp, (863,25))
    Image2.save("profile.png")
    
    await ctx.send(f"Hey {ctx.author.mention}, welcome to A **Cable Booth!**")
    await ctx.send(file = discord.File("profile.png"))
    print("Now2")
velvet tinsel
#

"guys my code broke"
"how did it break"
"well it did?"

#

wtf

royal jasper
#

what is the max messages that the bot can delete? (in ctx.channel.purge)

velvet tinsel
#

idk i've never experimented with it before

hushed galleon
#

it will use whatever techniques are available to delete as many messages as specified

pliant gulch
hushed galleon
#

either bulk deleting 100 at a time or deleting each one manually when older than 2 weeks

hushed galleon
slate swan
slate swan
slate swan
pliant gulch
#

Discord.py will just do the call multiple times when passing above that amount though

slate swan
#

@slate swan u up for making 30k+ lines for ai chat? PB_lmao_sweat

#

hey

#

hey

#

i need some help

#

with down_syndromesmile?

#

error -```py
main.py:62: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

code - ```py
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')
torn sail
#

you need to await it

slate swan
#

oki

#

ii put await in front of client right

slate swan
#

says its a outside fuction

#

cant spell rn

#

LOL

#

do that inside on_ready event?

#

alr

#

worked

#

good!

#

wait

#

no its sitll

#

doiong it

#

@slate swan

#

same error?

#

yes

#

ion think it should raise the same error since its inside the function

#

idk man

#

wuts the error?

slate swan
#

async def load_scripts():
await clinet.load.....

#

that?

#

then call the fucntiom

#

scripts?

#

Make a async await and call it

slate swan
#

client*

slate swan
slate swan
#

Same error?

#

same error

#

onreasy?

#

On ready

#

yes

#

Typo

#

i did yes

#

How many cogs do you havw

#

3

slim ibex
#

whats the issue

slate swan
#

atm

slate swan
#

okay so just put at the end of the script
clinet.load_extension(“cogs.filename”)

#

For each file

#

holy alr

slim ibex
#

i probably wouldn't load cogs in on_ready

slate swan
#

yeah @slate swan told me too lol

slate swan
slim ibex
#

it can be fired multiple times

slate swan
#

what should i do

slim ibex
#

yeah its a coroutine

#

what is your current code?

slate swan
#

i took it out of on ready

slate swan
#

so ```py
for filename in os.listdir('./cogs'):
await client.load_extension(f'cogs.{filename[:-3]}')

#

That will fix it

slim ibex
#

ah wait

slate swan
#

Trust me

slim ibex
#

discord.Client doesn't have cogs

slate swan
#

hm

slate swan
slim ibex
#

if you are instantiating a Bot instance in a variable named client that is bad code

#

it is confusing to anyone helping you

slate swan
slate swan
#

commands.bot

#

so ```py
for filename in os.listdir('./cogs'):
await client.load_extension({filename[:-3]}')

slim ibex
#

pls name the var bot

slate swan
#

Try this

#

Remove the await

slate swan
#
      for filename in os.listdir('./cogs'):
        client.load_extension({filename[:-3]}')
void elm
#

why wont discord import? i have it installed and updated

hushed field
hushed field
#

im assuming since load_extension is a coro, your on 2.0

slim ibex
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
slim ibex
#

it must be awaited

slate swan
#

Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "main.py", line 26, in on_message
if spawns in message.content and message.channel.id == "903028441102827540":
TypeError: 'in <string>' requires string as left operand, not list

slate swan
slate swan
#

code:

@bot.event
async def on_message(message):
  spawns = ["raider", "raid", "dynamax", "Multibattle", "**BREAK**", "**rare**"]
  if spawns in message.content and message.channel.id == "903028441102827540":
    await message.channel.send("@everyone something spawned here lol. go check")```
#

🤌

slim ibex
#

message.content is a list

slate swan
hushed field
slim ibex
#

list can't be compared with string

hushed field
#

nho

#

where are you currently loading the cogs?

slate swan
#

OHOH

slim ibex
#

what is your file structure relative to the file you are loading the cogs

slate swan
#

im so stupid im cryingwait a minute

slate swan
slim ibex
hushed field
#

no

slate swan
#
      for filename in os.listdir('./cogs'):
        client.load_extension(f'{filename[:-3]}')
hushed field
#

read the error correctly

slate swan
#

ill try

slim ibex
#

it is with your in statemenet

hushed field
slate swan
slate swan
hushed field
#

@slate swan again, for clarification, your on dpy 2.0

#

this is a simple solution, and everyone is making it hard

slim ibex
#

as @hushed field said, you need to iterate through your list and check if any element is in the message.content, @slate swan

slate swan
#

yeah

slim ibex
#

...

slate swan
#

im being srs

oblique laurel
#

Bad time for me to join the channel lol

hushed field
# slate swan yeah

ok, overrise the setup_hook function which is async, then await all your load_extensions etc. you can also set uptime attributes and all, setup_hook is fired ONCE and never again unless you restart

slate swan
#

im hebrew so not quite familar with some american words

slim ibex
slate swan
#

🤷

hushed field
slim ibex
#

!e

a = [1, 2, 3, 4]
for n in a:
  print(n)
unkempt canyonBOT
#

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

001 | 1
002 | 2
003 | 3
004 | 4
hushed field
#

learn python

slate swan
#

oy ok sir

slim ibex
#

you are iterating over list a to find elements n

slate swan
#

yeah ik what u were talking abt i didnt know

slate swan
#

that what u were like saying

#
async def main():
  async with client:
    for file in os.listdir("./cogs"):
      await client.load_extension(f"{file[:-3]}")
      await client.start(token)
hushed field
hushed field
slim ibex
#

^

slate swan
#

where do i put that

hushed field
#

bro

#

i said to OVERRIDE IT

slate swan
#

OH ok

#

kk ima test this

slate swan
#
@bot.event
async def on_message(message):
  spawns = ["raider", "raid", "dynamax", "Multibattle", "**BREAK**", "**rare**"]
  for n in spawns
  if spawns in message.content and message.channel.id == "903028441102827540":
    await message.channel.send("@everyone something spawned here lol. go check")```
hushed field
slate swan
#

says invalid syntax

hushed field
#

no shit

slate swan
hushed field
#

learn python

slate swan
#

learn english

#

btw ik python

hushed field
slate swan
#

its just like yk

hushed field
#

no you dont

slate swan
#

bruh yes i do just help me with this thing

hushed field
#

no, you dont. iteration is simple, let alone the syntax

slate swan
#

alr fixed it

#
@bot.event
async def on_message(message):
  spawns = ["raider", "raid", "dynamax", "Multibattle", "**BREAK**", "**rare**"]
  for n in spawns:
    if spawns in message.content and message.channel.id == "903028441102827540":
      await message.channel.send("@everyone something spawned here lol. go check")```
hushed field
#

L

slim ibex
#

watch

slate swan
#

bruhh

#

whats the point of the for n in spawns?

hushed field
slate swan
#

its been a while since i coded in python

#

like 7 months ago

slate swan
#

There is no point

slate swan
#

😦

hushed field
#

again, you dont know python

slate swan
slim ibex
#

bnru

slate swan
#

and i do know python

hushed field
#

no, you dont

slate swan
#

also i do know python

#

its not a fucking spelling class

hushed field
#

notice how i purposely spelt it incorrectly to make you correct me

slate swan
#

holy shit bro DEAD

#

!any

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
slate swan
#

IM SO gay YOUR NUT

hushed field
#

roblox ✅
doesnt know python ✅
corrects for no reason ✅

is 12 years old ✅

slate swan
hushed field
#

i didnt ask

slate swan
#

also whats wrong abt roblox + im not 12

hushed field
#

Ok. Learn some python.

slim ibex
#

everything is wrong with Roblox

slate swan
#

I DO KNOW python

hushed field
#

no, you dont

oblique laurel
slate swan
oblique adder
#

there are duplicate commands , how do i remove ?

hushed field
slate swan
oblique adder
hushed field
#

what event

#

and i assume your specifying a guild param

slim ibex
oblique adder
#

is that the prob ?

slate swan
#

alr heres my code

hushed field
slate swan
#
@bot .event #line:1:@bot.event
async def on_message (O000000000O0O0000 ):#line:2:async def on_message(message):
  O000O0O00000OOOOO =["raider","raid","dynamax","Multibattle","**BREAK**","**rare**"]#line:3:spawns = ["raider", "raid", "dynamax", "Multibattle", "**BREAK**", "**rare**"]
  for O00OOOO0OO00O0O00 in O000O0O00000OOOOO :#line:4:for n in spawns:
    if O000O0O00000OOOOO in O000000000O0O0000 .content and O000000000O0O0000 .channel .id =="903028441102827540":#line:5:if spawns in message.content and message.channel.id == "903028441102827540":
      await O000000000O0O0000 .channel .send ("@everyone something spawned here lol. go check")```

*obsfucated so nobody can steal*
hushed field
#

yup, your trolling

oblique adder
slate swan
#

just bc i dont want anyone to steal my code

slim ibex
#

we can't even help you with obfuscated code

slate swan
#

oh u right

slate swan
#

oops sorry forgot to undo

oblique laurel
slim ibex
#

i can ping mods rn if you are actually trolling

slate swan
#
@bot.event
async def on_message(message):
  spawns = ["raider", "raid", "dynamax", "Multibattle", "**BREAK**", "**rare**"]
  for n in spawns
  if spawns in message.content and message.channel.id == "903028441102827540":
    await message.channel.send("@everyone something spawned here lol. go check")```
#

it said i tried to ping everyone bc i forgot

slim ibex
#

...

hushed field
#

learn python please

slate swan
#

what tf did i do now

hushed field
slim ibex
#

invalid syntax

hushed field
#

^ Learn Python!

oblique laurel
#

I mean dont u have an ide that highlights syntax?

slate swan
slate swan
slate swan
oblique laurel
hushed field
#

LOL

slate swan
#

lmk

hushed field
#

ill let you know,

|| learn python ||

slim ibex
slate swan
hushed field
#

please what?

slate swan
#

i saw all the replit tutorials

#

idk man it wont let me

hushed field
#

but not the python tutorials

#

sucks, use a proper ide and a proper vps

slate swan
oblique laurel
#

Yt bot tutorials suck lol

slate swan
#

This guy is a turk teaching us about english

#

repl.it ---- the website i used for my coding
FOLLOW MY SOCIAL MEDIAS :
instagram : steven.miall
snapchat : smiall5

▶ Play video

Hi there!

In this video, "Getting Started with Repl.it", we'll go over how to get started with repl.it/Replit's online IDE and code editor. We'll get coding in no time, and then review how to share links/projects/ and code examples with friends, colleagues, or collaborators so that you can code together in real-time, should the occasion come up...

▶ Play video
#

they are good

oblique laurel
#

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

oblique laurel
#

Odds are any tutorial name in all caps is 100% tryna get views and not actually help lol

slate swan
#

oh and could u help

oblique laurel
#

W wut

slate swan
#

my issue

oblique laurel
#

Ur issue isnt bot related, but syntax related

slate swan
oblique laurel
#

Shhh tryna have a laugh lol

slate swan
#

i swear on judaism

slate swan
oblique laurel
#

Ah see i wqs thinking u were a troll, but now im convinced ur fr

slate swan
#

please just help me i promise to everything i just wanna make a bot

#

oh my god you guys are so disrespectful

slate swan
#

where are the mods

#

im being genuine

oblique laurel
slate swan
#

will do

#

after u help

#

now pleaseee

oblique laurel
#

Tempting

slate swan
#

oh my goddd

slate swan
oblique laurel
#

Then how do u not know that a for loop needs indents -_-

slate swan
slate swan
#

u guys were right

hushed field
#

nahhh

slate swan
#

it was pretty simple

formal thistle
#

hi mans

inland shell
#

anyone down to make a discord bot for me? for fun. some extra practice.

oblique laurel
#

This aint fiverr lol

supple thorn
oblique laurel
slate swan
slate swan
#

was easy

slate swan
#
@bot.event
async def on_message(message):
  if "raider" in message.content:
      await message.channel.send("@everyone something spawned here lol. go check")
  elif "raid" in message.content:
      await message.channel.send("@everyone something spawned here lol. go check")
  elif "dynamax" in message.content:
      await message.channel.send("@everyone something spawned here lol. go check") 
  elif "Multibattle" in message.content:
      await message.channel.send("@everyone something spawned here lol. go check")
  elif "**BREAK**" in message.content:
      await message.channel.send("@everyone something spawned here lol. go check")
  elif "**rare**" in message.content:
      await message.channel.send("@everyone something spawned here lol. go check")
  await bot.process_commands(message)
#

works like glue

oblique laurel
#

This hurts my soul lol

slate swan
slim ibex
#

what the fuck

slate swan
#

did i do this time i thought you'd be proud of me

#

it works

oblique laurel
#

Great job 👍

slate swan
#

alr thanks

slate swan
#

i did it myself:(

slim ibex
#

you can use a for loop my guy

slate swan
oblique laurel
#

Bro fr take a python course

#

Cant tell u how much pain thatll save u

slim ibex
#

andy

pliant gulch
#

You don't even need a for loop, you could just check multiple strings in one if statement

#

!d any would work

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
pliant gulch
#

Although it does use a for loop internally

slate swan
oblique laurel
slate swan
#

but ig it could save me about 10 seconds 💀

oblique laurel
#

Theres getting it done, and theres getting it done well

slate swan
#

just being plain lazy

#

thats what well means to u?

oblique laurel
#

?

slim ibex
#

??????

pliant gulch
# unkempt canyon

If you don't want to use any you can also use sets, E.g ```py
if set("raider", ...).intersection(set(message.content.split())):
...

slate swan
#

btw for hosting i use
freshping

slate swan
#

to take the easy route, which is easy

oblique laurel
#

Ye

slate swan
#

and i cud do the harder way

#

bc im not lazy,

#

my hosting is so gud

oblique laurel
#

"I choose a lazy man to do a hard job. Because a lazy person will find an easy way to do it.” -Bill Gates

slate swan
#

50 pings per minute

oblique laurel
#

How does…? Nvm not even gonna try to ask

velvet compass
supple thorn
#

how do you check if the guild on a on_member_join is a specific guild

inland shell
#

anyone know the code to make a discord bot send a new message when a new channel is created in that new channel

oblique laurel
#

Member.guild returns the guild

supple thorn
#

i tried that

#

that's the first thing i tried

oblique laurel
#

Should rlly be the only thing you try lol. The breakage was somewhere else then

supple thorn
#

but i'm having a suspicion that my event isn't getting triggered

#

new bot fuck

#

i forgot intents

oblique laurel
#

My pro highlighting skills lol

#

But ye fr, check the docs more lol. Odds are thats what ppl in here would do to answer anyways

brave flint
#

well i wanna do that too

#

XD

velvet compass
#

Yeah but their use case is extremely suspicious to me

inland shell
#

how do u make a command create a text channel like: /ticket

inland shell
oblique laurel
#

When someone types the command, you create the channel lol. You alr said it

inland shell
#

can u help me with this code on replit im new

sick birch
#

Why replit?