#discord-bots

1 messages · Page 1030 of 1

stone beacon
#

First time hearing about that one, gl!!

glad palm
#

haha

#

thanks!

pliant gulch
#

You'd just need to think about bandwith usage, but that's still gonna be pretty minimal

#

Most servers offer unlimited bandwith nowadays after all

glad palm
#

well, nearly infinite

pliant gulch
#

Yea, for an example I know digital ocean does that iirc?

analog matrix
#
                file = json.dumps(ids).replace('{', ',', 1)
                f.seek(-2,2)
                f.write(file)```
jade tartan
#

What do I do?

#

Anyone

#
async def button(ctx, InteractionType, member=discord.Member):
    channel = client.get_channel(904279966693355550)
    embed = discord.Embed(title="Add role",
                                   description=f"Do you want to add this role?",
                                   color=discord.Colour.green())
    await ctx.reply(embed=embed, components=[
                [Button(style=ButtonStyle.green, label="Add")]])
    res = await client.wait_for("button+_click")
    if res.component.label == "Add":
            await channel.send(embed=embed)
            await ctx.reply("Role has been sent!")
    else:
            await ctx.reply("You're not permitted to use this command!")
hybrid fjord
#

am i going mad??

#

the channel is there and the bot can see it and i double checked the id

pliant gulch
# hybrid fjord am i going mad??

Tasks get loaded before a bot's interal cache get's populated. That means in this current context there are no channels in the cache, leading get_channel to return None. Just smack await Bot.wait_until_ready() before the call to get_channel and it should work

hybrid fjord
#

ah

pliant gulch
hybrid fjord
#

sounds good. thanks

pliant gulch
#

👍

slate swan
#
    await ctx.send(embed = help, 
                   components = [Select
                                 (placeholder = "choose...",
                                       options=[
                                         SelectOption(label = "option 1",
                                                      value = "option1",
                                                      description = "See option 1",
                                                      emoji = "🌸"
                                                     ),
                                         SelectOption(label = "Option 2",
                                                      value = "option2",
                                                      description = "See option 2",
                                                      emoji = "🌸"
                                                     ),
                                       ])]
                  )
    e1 = Embed(title="embed1", description="yes")
    e2 = Embed(title="embed2", description="yes")
    e3 = Embed(title="embed3", description="yes")
    
    while True:
      try:
        event = await self.bot.wait_for("select_option", check = None)
        
        label = event.component[0].label
        
        if label == "Option 1":
          await event.respond(
            type = InteractionType.ChannelMessageWithSource,
            ephemeral = True,
            embed = e1
          )
          
        elif label == "Option 2":
          await event.respond(
            type = InteractionType.ChannelMessageWithSource,
            ephemeral = True,
            embed = e2
          )
        print("error.")

Does anyone know why this code is not working?

jade tartan
#
async def button(ctx, InteractionType, member=discord.Member):
    channel = client.get_channel(904279966693355550)
    embed = discord.Embed(title="Add role",
                                   description=f"Do you want to add this role?",
                                   color=discord.Colour.green())
    await ctx.reply(embed=embed, components=[
                [Button(style=ButtonStyle.green, label="Add")]])
    res = await client.wait_for("button+_click")
    if res.component.label == "Add":
            await channel.send(embed=embed)
            await ctx.reply("Role has been sent!")
    else:
            await ctx.reply("You're not permitted to use this command!")
#

Any one?

slate swan
#

its button_click , not button+_click

slate swan
#

Use views!!!

stiff gorge
#
    @commands.command()
    @commands.cooldown(1, 10, commands.BucketType.user)
    async def timer(self, ctx: commands.Context, seconds):
      secondint = int(seconds)
      if secondint < 1 or secondint > 300:
        embedVar = discord.Embed(title='Timer',description=":Timer:" + " : " + " please use range between 1-300s",color=0x2f3136)
        await ctx.send(embed=embedVar)
      else:
        embedVar = discord.Embed(titel='Timer', description=":Timer:" + " Remaining : " + f"{seconds}",color=0x2f3136)
        message = await ctx.send(embed=embedVar)
        await asyncio.sleep(1)
        for i in range(secondint - 1, -1, -1):
          embedVar = discord.Embed(title='Timer',description=":Timer:" + " Remaining : " + f"{i}",color=0x2f3136)
          await message.edit(embed=embedVar)
          await asyncio.sleep(1)
          await message.delete()
          embedVar = discord.Embed(title='Timer',description=f"{ctx.author.name} Your countdown " + f"{seconds}s " + "Has ended!",
                    color=0x2f3136)
          embedVar.set_thumbnail(url=
                                   'https://cdn.discordapp.com/attachments/969178492002500678/971001114046627900/stopwatch_1.png')
          await ctx.send(f'{ctx.author.mention}',embed=embedVar)
        except ValueError:
          embedVar = discord.Embed(title='Invalid Argument',description=f"• Please use range between 1-300s \n • Please put in a valid option! Example: `{prefix}timer <number>` ",color=0x2f3136)
          await ctx.reply(embed=embedVar)

why does it say invalid syntax

stiff gorge
#

except ValueError:

supple thorn
stiff gorge
#

ohk

supple thorn
unkempt canyonBOT
#

A key part of the Python philosophy is to ask for forgiveness, not permission. This means that it's okay to write code that may produce an error, as long as you specify how that error should be handled. Code written this way is readable and resilient.

try:
    number = int(user_input)
except ValueError:
    print("failed to convert user_input to a number. setting number to 0.")
    number = 0

You should always specify the exception type if it is possible to do so, and your try block should be as short as possible. Attempting to handle broad categories of unexpected exceptions can silently hide serious problems.

try:
    number = int(user_input)
    item = some_list[number]
except:
    print("An exception was raised, but we have no idea if it was a ValueError or an IndexError.")

For more information about exception handling, see the official Python docs, or watch Corey Schafer's video on exception handling.

stiff gorge
supple thorn
stiff gorge
#
    @commands.command()
    @commands.cooldown(1, 10, commands.BucketType.user)
    async def timer(self, ctx: commands.Context, seconds):
      try:
        secondint = int(seconds)
        if secondint < 1 or secondint > 300:
          embed = discord.Embed(title='Timer',description=":Timer:" + " : " + " please use range between 1-300s",color=0x2f3136)
          await ctx.send(embed=embed)
        else:
          embed = discord.Embed(titel='Timer', description=":Timer:" + " Remaining : " + f"{seconds}",color=0x2f3136)
          message = await ctx.send(embed=embed)
          await asyncio.sleep(1)
          for i in range(secondint - 1, -1, -1):
            embed = discord.Embed(title='Timer',description=":Timer:" + " Remaining : " + f"{i}",color=0x2f3136)
            await message.edit(embed=embed)
            await asyncio.sleep(1)
            await message.delete()
            embed = discord.Embed(title='Timer',description=f"{ctx.author.name} Your countdown " + f"{seconds}s " + "Has ended!",
                    color=0x2f3136)
            embed.set_thumbnail(url=
                                   'https://cdn.discordapp.com/attachments/969178492002500678/971001114046627900/stopwatch_1.png')
            await ctx.send(f'{ctx.author.mention}',embed=embed)
      except ValueError:
        embed = discord.Embed(title='Invalid Argument',description=f"• Please use range between 1-300s \n • Please put in a valid option! Example: `{prefix}timer <number>` ",color=0x2f3136)
        await ctx.reply(embed=embed)

    @timer.error
    async def timer_error(self, ctx, error):
      if isinstance(error, commands.CommandOnCooldown):
        embed = discord.Embed(color=0x2f3136,title="Slow it down buddy",description=f" Try again in {error.retry_after:.2f}s")
        embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/969178492002500678/971001114046627900/stopwatch_1.png')
        await ctx.reply(embed=embed) 

supple thorn
stiff gorge
#

this after it ends

#

just the cooldown embed works

supple thorn
stiff gorge
#

yes

#

it will send a embed first then delete tht and send a new embed

supple thorn
#

Why is that embed in the timer

supple thorn
#

Isn't that embed supposed to be only sent after the timer is done

#

That embed would get sent every time

stiff gorge
#

1st embed the live countdown is shown when the countdown ends it delets tht embed and sends the 2nd embed

supple thorn
#

When it's in the loop

#

And there's nothing saying that it should only send if timer is 0

stiff gorge
#

ohk ty ill fix it

slate swan
#

how can i get the name of the server from which a user triggers the on_member_join event?

#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

Hi skev hru

#

ah bet

supple thorn
#

!d discord.Member.guild

unkempt canyonBOT
slate swan
supple thorn
unkempt canyonBOT
supple thorn
slate swan
#

bet ty

#

sexy

#

..

supple thorn
slate swan
supple thorn
#

Bad

#

Cause i didn't get to eat noodles

slate swan
#

..

stray carbon
#
class HelpDropdown(nextcord.ui.Select):
    def __init__(self, help_command: "PaginatedHelpCommand", options: List[nextcord.SelectOption]):
        super().__init__(placeholder="Choose a category", min_values=1, max_values=1, options=options)
        self.help_command = help_command
    
    async def callback(self, interaction):
        embed = await self.help_command.cog_help_embed(self.help_command.context.bot.get_cog(self.values[0].lower()))   
        pages = HelpButtonMenuPages(
            ctx=self.help_command.context,
            source=HelpPageSource(self.help_command, self.help_command.embed_fields),
            message=interaction.original_message,
            disable_buttons_after=True
        )
        await pages.start(interaction.original_message)
#

await item.callback(interaction)
File "C:\Users\Akai\Desktop\Sugari\cogs\info.py", line 19, in callback
await pages.start(interaction.original_message)
File "C:\Users\Akai\AppData\Local\Programs\Python\Python38\lib\site-packages\nextcord\ext\menus\menu_pages.py", line 145, in start
await super().start(
File "C:\Users\Akai\AppData\Local\Programs\Python\Python38\lib\site-packages\nextcord\ext\menus\menus.py", line 675, in start
self.bot = ctx.bot
AttributeError: 'function' object has no attribute 'bot'

#

Need help here

#

im trying to make the dropdown edit current message on interaction

#

instead of sending

midnight gorge
torn sail
#

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

midnight gorge
#

it could me a db error tho

slate swan
#

Have you even tried to debug yourself? See if it really gets inserted/updated, see the message result you would get in the event, etc. etc.

glad cradle
dull terrace
#

does this mean that because i didn't use async database that it's gonna break if i have to shard my bot 7739monkathink

glad cradle
slate swan
#

Those are placeholders that will get replaced later by the bot in the welcome message. It's for people to set up their welcome message and have variables and specific things shown in their welcome message rather than just a "Welcome new user". So when setting the welcome message you can put, for example,{members} so that it gets replaced with the number of members in the server. And as you can see, the message sent is "welcome message set to:", which means that's not the message sent when a new member joins the server.

stray carbon
#
    async def callback(self, interaction):
        embed = await self.help_command.cog_help_embed(self.help_command.context.bot.get_cog(self.values[0].lower()))
        pages = HelpButtonMenuPages(
            ctx=self.help_command.context,
            source=HelpPageSource(self.help_command, self.help_command.embed_fields, self.help_command.context.bot.get_cog(self.values[0].lower())),
            help_command=self.help_command,
            options=await self.help_command.cog_select_options(),
            message=await interaction.original_message(),
            disable_buttons_after=True
        )
        await pages.start(interaction=interaction)

nextcord\ui\view.py", line 371, in scheduled_task
await item.callback(interaction)
File "C:\Users\Akai\Desktop\Sugari\cogs\info.py", line 18, in callback
message=await interaction.original_message(),
File "C:\Users\Akai\AppData\Local\Programs\Python\Python38\lib\site-packages\nextcord\interactions.py", line 330, in original_message
data = await adapter.get_original_interaction_response(
File "C:\Users\Akai\AppData\Local\Programs\Python\Python38\lib\site-packages\nextcord\webhook\async
.py", line 189, in request
raise NotFound(response, data)
nextcord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

supple thorn
#

Hi kryp

vale wing
slate swan
#

how to make timeout cmd

vale wing
#

You need something not dpy 1.7

#

Dpy 2.0 or a fork that supports timeouts

#

or just make raw request to discord api

maiden fable
slate swan
stray carbon
#

,

#

fixed

slate swan
#

i need timeout cmd

zenith mural
slate swan
#

-_-

stray carbon
supple thorn
unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

supple thorn
#

Wondering why i never heard of that

dry crown
#

how does discord.AutoSharded work?

vale wing
#

It does shards

supple thorn
vale wing
#

😩

dry crown
supple thorn
#

Carlbot?

supple thorn
visual island
dry crown
vale wing
keen mural
slate swan
#

yea

stray carbon
#

ctx in slash command???

slate swan
#

lol

stray carbon
#

i guess you mean @bot.command()

#

then you have to rewrite it

slate swan
#

in @bot.command()

#

on what u making?

slate swan
glad cradle
#

you can't use ctx.respond in a slash cmd interaction

#

inter.response.send_message

#

replace ctx with inter in the parameters

#

to send message after an interaction

await inter.response.send_message(embed=embed...)

replace all your occurrences where you use ctx.respond

slate swan
#

like u making giveaway bot?

#

-_--

#

lol

#

so my little boy what do you need about help?

#

now?

slate swan
#

i already now?

#

-_-

#

lol

#

im not boy-_-

#

i don't lie

#

mhm

#

nah

#

im better

#

dm to see?

glad cradle
#

I was searching interaction in discord.py documentation but I did not find anything, I can't help you for slash command if you use discord.py, I know disnake

#

ic

slate swan
#

why dont you accept all the info while invoking the command?

#

why would you use wait_fors?

#

otherwise you could use modals and views, would be better

#
async def foo(ctx, channel: discord.TextChannel, ...): ...```
#

Here is a short example of how to use discord.py's slash commands as well as general information on them:

https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f

This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.

Gist

discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.

#

(totally copied from the dpy server)

#

they didn't add an example to their own repo yet, bad.

#

very

visual island
#

Feel free to make a PR to the library, would be really appreciated

slate swan
#

i think uh

#

hmmm

ornate beacon
#

Hi

slate swan
#

like who hosted?

#

like this
Hosted by:{user}?

#

just mention/display their name using the mention/name property

#

afk

ornate beacon
#

Who can help me learn python xd I wanna make discord bots

ashen perch
#

hey does anyone know if there is a limit to how many sub commands you can add to a slash command ?

slate swan
#

on 10 mins

ornate beacon
ashen perch
#

wait ill send picture i think it will be easier

#

so like this

slate swan
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.

ornate beacon
#

Ok

#

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

slate swan
#

back

#

front

visual island
#

Actually, it's 25

ornate beacon
slate swan
#

You can use the filters. Since you don't know anything you probably want to go for beginner and no topic filter. Just choose the type of learning you like and you will get some useful resources.

vital whale
#

I too made the dumb mistake of finding and changing this

#

didn't do anything and still returns the error and HTTPException

stiff gorge
#
  File "/home/runner/mvp/cogs/cr.py", line 35, in crsave
    ezjson.dump("data/crtags.json", ctx.author.id, crtag)
  File "/home/runner/mv/venv/lib/python3.8/site-packages/ezjson.py", line 17, in dump
    return Json.encode(o, date_format, max_depth)
  File "/home/runner/mv/venv/lib/python3.8/site-packages/ezjson.py", line 111, in encode
    out = self.__normalize(o)
  File "/home/runner/mvp/venv/lib/python3.8/site-packages/ezjson.py", line 56, in __normalize
    json = self.__build_js_values(o)
  File "/home/runner/mvp/venv/lib/python3.8/site-packages/ezjson.py", line 62, in __build_js_values
    if type(v) in (bool, int, long, float, str, unicode, decimal.Decimal, datetime.datetime, datetime.date, datetime.time) or v is None:
NameError: name 'long' is not defined

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

Traceback (most recent call last):
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1329, in invoke
    await ctx.command.invoke(ctx)
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 990, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/mv/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 209, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'long' is not defined

how do i save author id and text in json ?

slate swan
#

use sqlite/postgreSQL/MySQL/MongoDB

stiff gorge
#

ok

bronze lark
#
@bot.command()
@commands.has_permissions(ban_members=True)
async def term(ctx, member:discord.User = None, reason =None):
    if member == None or member == ctx.message.author:
        await ctx.channel.send("You cannot ban yourself")
    return
    if member == None:
        embed = discord.Embed(title='Termixovvý výsledek:')
        embed.add_field(name=':white_check_mark: | Povedene operace', value=f'`žádna neni`')
        embed.add_field(name=':x:| Nepovedená operace', value='`nemám komu dat termix`')
        await ctx.send(embed=embed)
    return
    if reason is None:
        esu = discord.Embed(title='Termixovvý výsledek:')
        esu.add_field(
            name=':white_check_mark: | Povedene operace',
            value=f'`žádna neni`')
        esu.add_field(name=':x:| Nepovedená operace', value='Nedal jsi reason takže nemůžu pokračovat')
        await ctx.send(embed=esu)
    return
  File "C:\Users\magic\Desktop\Discord Bot-\Hlavni.py", line 34
    embed.add_field(name=':white_check_mark: | Povedene operace', value=f'`žádna neni`')
                                                                                                              ^
IndentationError: unindent does not match any outer indentation level

Process returned 1 (0x1)        execution time : 0.071 s
Press any key to continue . . .
#

please help me

#

@stiff gorge do you know?

shrewd apex
#

chem over!!

shrewd apex
bronze lark
#

what is it?

#

like this?

#

@shrewd apex

shrewd apex
#

yes

supple thorn
shrewd apex
#

write the add field all in one line

#

then try re running

supple thorn
#

Hello kayya

#

Nothing much i'm reading a manga that's about a dude trying to get revenge on a woman that broke their contract

#

Pretty much ditched him

#

He then goes to the uni she's at to act his plan

#

Wanna read it too

#

Pretty good ig it only has 58 chapters though but it's still being continued i think

#

remembers your anime avatars

bronze lark
supple thorn
#

Maybe you haven't found the right one

#

What do you like

shrewd apex
stray carbon
bronze lark
shrewd apex
#
embed.add_field(name=name, value=value, inline=inline)
#

channel is just the channel ID

#

it's a single channel object

#

how can u iterate it

#

if u want to get channel for whole guild

#

use for channel in ctx.message.guild.channels then iterate

crimson compass
#
    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")
    if message.content.startswith('!time'):
        await message.channel.send("Current Time =", current_time)
#

Error:

   await message.channel.send("Current Time =", current_time)
TypeError: Messageable.send() takes from 1 to 2 positional arguments but 3 were given
formal basin
#

Why is this an invalid synax

glad cradle
paper sluice
formal basin
#

Oh

glad cradle
#

new_whitelist['key'] = data

slate swan
#

Can u make a certain cooldown for each role in one command?

formal basin
#

In my json file

#

How do I do an if statement for my channel id

#

In json file

white citrus
#

Heyo i habe a problem can someone help?

supple thorn
#

Don't ask to ask

formal basin
#

Like if the message is in this channel then if that channel is in json file
return

white citrus
#

I have a bot.process but my prefix is ​​m and it also sends it for example when I send muscles but that's not a command. he should only do it with commands

white citrus
#

It also reacts to normal messages although it should only react to commands

white citrus
supple thorn
#

Or atleast have a symbol with the prefix

#

Like m!

white citrus
supple thorn
supple thorn
#

like m! or m+

white citrus
#

That shouldn't matter

supple thorn
#

Prefix are meant to be not triggered in normal conversations

#

That's why they're made like that

supple thorn
maiden fable
cunning flame
#

so im trying to create a bot that calculates prices but when I leave a space in the first argument it will not work, how can I fix this?

@client.command(
    help="Use ?price (item) (quantity) (price)",
    brief="Checks item price",
    category="basic"
)


async def price(ctx, a: str, b: int, c: float):   # a is item ; b is quantity ; c is price
    itemPrice = (b*c)-((b*c)*0.0275)
    embed = discord.Embed(title= a+" price", description= "The price for "+a+" is "+str(itemPrice)+" Credits", color =0x4446d1)
    embed.set_footer(text="Created by V.#4181")
    await ctx.send(embed=embed)
formal basin
#

All I need is an if statement of if message in this channel if that channel.id is in the json file
return

bronze lark
#
@bot.command()
@commands.has_permissions(ban_members=True)
async def term(ctx, member:discord.User = None, reason =None):
    if member == None or member == ctx.message.author:
        await ctx.channel.send("You cannot ban yourself")
    if member == None:
        embed = discord.Embed(title='Termixovvý výsledek:')
        embed.add_field(name=':white_check_mark: | Povedene operace', value=f'`žádna neni`')
        embed.add_field(name=':x:| Nepovedená operace', value='`nemám komu dat termix`')
        await ctx.send(embed=embed)
    return
    if reason is None:
        esu = discord.Embed(title='Termixovvý výsledek:')
        esu.add_field(
            name=':white_check_mark: | Povedene operace',
            value=f'`žádna neni`')
        esu.add_field(name=':x:| Nepovedená operace', value='Nedal jsi reason takže nemůžu pokračovat')
        await ctx.send(embed=esu)
    return

error

  File "C:\Users\magic\Desktop\Discord Bot-\Hlavni.py", line 33
    embed.add_field(name=':white_check_mark: | Povedene operace', value=f'`žádna neni`')
                                                                                          ^
IndentationError: unindent does not match any outer indentation level

Process returned 1 (0x1)        execution time : 0.067 s
Press any key to continue . . .


#

@formal basin do you know?

formal basin
#

Can I see a picture of your code

#

That code

bronze lark
#

yes

slate swan
formal basin
slate swan
formal basin
slate swan
#

Might want to put it inside the if statement

if x:
    # Some stuff
    return

and not

if x:
    # Some stuff
return
bronze lark
#

ok

#

like this?

formal basin
bronze lark
#
    if reason is None:
        esu = discord.Embed(title='Termixovvý výsledek:')
        esu.add_field(
            name=':white_check_mark: | Povedene operace',
            value=f'`žádna neni`')
        esu.add_field(name=':x:| Nepovedená operace', value='Nedal jsi reason takže nemůžu pokračovat')
        await ctx.send(embed=esu)
        retrun
slate swan
#

i need some help sending info from my api to my bot: im sending a webhook with a special tag in it so that my bot can pick it up
and then it strips the special tag from the message, leaving it with only the userID i make the api send. i need to also send a serverid with it, how can i do so?
tldr: be able to parse 2 separate ids from a string

formal basin
bronze lark
#

@formal basin did you find enythig?

formal basin
bronze lark
#

thats will be in group tabs

slate swan
#

Then split with :

#

ah good idea

bronze lark
#

@slate swan did you find enythig?

slate swan
bronze lark
#

atom

slate swan
#

Select all the code

#

Any recommendations for an online py code executor for ios? i can’t use my pc rn and need to do some quick tests

#

Go to Edit->Lines-> Auto Indent

slate swan
#

ye

bronze lark
#

now?

slate swan
#

You can use !e in #bot-commands

#

oh ig

#

but formatting gonna be annoying, il still give it a shot

supple thorn
#

So it'll be

supple thorn
#

Yellow Stone will be considered as the first argument using the quotes

cunning flame
#

mm okay

slate swan
#

Or you can reverse

#

Like put "Yellow Stone" at the end

modern fiber
#

Hey guys, how do I add a description to an commands on default help command?

slate swan
modern fiber
#

do I just use description= or?

slate swan
#

Yea I believe so

#

who can help me?

#

Nobody if you don't give a question

#
@commands.command()
    async def pay(self, ctx, member: discord.Member, amount: int):
        emb=discord.Embed(description=f"**{ctx.author}** handed over **{amount}**:money: user **{member}**", colour=discord.Color.gold())
        embed=discord.Embed(description=f"The number must be greater **0**", colour=discord.Color.gold())
        ubalance=self.collection.find_one({"_id": ctx.author.id})["balance"]
        mbalance=self.collection.find_one({"_id": member.id})["balance"]
        if amount <= 0:
            await ctx.reply(embed=embed)
        else:
            self.collection.update_one({"_id": ctx.author.id},
            {"$set": {"balance": ubalance - amount}})
            self.collection.update_one({"_id": member.id},
            {"$set": {"balance": mbalance + amount}})
            await ctx.reply(embed=emb)```
#

That's some nice code

paper sluice
#

whats the problem?

slate swan
#

second

#

Now what's the issue KEKW

paper sluice
#

pithink what second?

slate swan
#

Probably need to wait a second

#

I need it to give money only if the person has that amount

bronze lark
#

@slate swan i have this its corect?

slate swan
paper sluice
slate swan
#

Ehm, <= not == - you still have amount if you have more money than that

#

hm

#

thx

bronze lark
#

nothiging error but bot not anservering

#

@slate swan

modern fiber
#

can I make bot do smth like
if role1 remove role2

#

for all users

#

it should be like an event

slate swan
#

After the return nothing will be executed

stiff gorge
#
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can't subtract offset-naive and offset-aware datetimes
passed = datetime.now() - ctx.guild.created_at
slate swan
# bronze lark

You have

if x:
    # Stuff
    return 
    # More stuff

You need

if x:
    # Stuff
    return 
# More stuff
stiff gorge
#

how can I subtract this

slate swan
#

Remove the timezone awareness

#

Or just add UTC as timezone

stiff gorge
#

ok ty

slate swan
#

For .now()

#

As right now .now() has your timezone but not ctx.guild.created_at

slate swan
bronze lark
#

i seeeee

slate swan
#

And for the first if statement, you probably want to also return

bronze lark
#

ok

slate swan
#

And just use ctx.send instead of ctx.channel.send

feral halo
#

hola what's goin on here

bronze lark
#

like this?

slate swan
#

How can I make it so that users on different servers have different balance?

#

Looks better, still need to return in the first if statement

slate swan
#

You can add an additional field like guild_id

#

?

#
# sestings
@bot.event
async def on_ready():
    print(f"{bot.user} is connected!")
    await bot.change_presence(status=discord.Status.idle, activity=discord.Game("K.help"))

    for guild in bot.guilds:
        for member in guild.members:
            post={
                "_id": member.id,
                "balance": 500,
                "xp": 0,
                "lvl": 1
            }
            if collection.count_documents({"_id": member.id}) == 0:
                collection.insert_one(post)```
#

Yeah see

bronze lark
#
if x:
    return
    # Stuf 
# More stuf
```?
slate swan
#

Just add a new field guild_id

bronze lark
#

like this?

slate swan
bronze lark
#

where?

slate swan
#

It's your code, isn't it?

bronze lark
#

its my code

slate swan
#

Then why don't you have consistency and use the same within your if statements

bronze lark
#

like this?

slate swan
#

No.

feral halo
#

i don't think return is necessary

slate swan
#

Your first if statment

slate swan
feral halo
#

where can i see the code

slate swan
#

Otherwise the code will continue executing at the bottom

bronze lark
slate swan
slate swan
feral halo
#

oh it's a command

slate swan
#

Just like every other you did

feral halo
#

i see now

bronze lark
slate swan
#

Your first

#

Not second

bronze lark
slate swan
#

Yes

bronze lark
#

nice

#

i try

slate swan
#

And you can just do return await ctx.... if you want

#

Instead of 2 lines

bronze lark
#

its ok

#

the long code its for flex

#

😎

slate swan
#

Spaghetti code is not flex at all

bronze lark
#

ik

feral halo
#

it's pain for us to read

slate swan
#

It's just overall horrible

bronze lark
#

nice its working tysm

maiden fable
#

@formal basin use the json module to access the json file and then use the in operator to access the list/dict

slate swan
#

Already said, read the JSON and interpret your list of IDs as list and check if the channel ID is in that list

formal basin
#

I am

slate swan
#

Then you have done it

slate swan
#

how can i check if a role exists in a guild?

slate swan
formal basin
slate swan
#

!e
c = 1337
ids = [1337, 7331]

if c in ids:
print("yay")

unkempt canyonBOT
#

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

yay
slate swan
#

Will help

formal basin
#

No in a json file

slate swan
#

Again.

glad cradle
#

ahahha

slate swan
#

Read the JSON file like in the link above and get your list.

slate swan
#

It's not rocket science, it's just trial and error. Just try to read the JSON, if that works try to get the list, etc. etc.

glad cradle
tough stone
#

Hey ! I created for my server my own muted role, with a command, but I want to specify in this command the duration of the mute, so when it comes to an end, it unmutes automatically. How can I do this ? Thanks !

glad cradle
#

explain better

slate swan
glad cradle
#

you can do this, but not in the same command function

slate swan
#

You can

tough stone
formal basin
#

with open(‘test.json, r’)
if channel.id in channel
return

slate swan
#

Hybrids commands can be used to make both slash commands and prefix commands with the same code and function

exotic maple
#

Hey, how do i let guild owners use cmds only? What do i say?

I tried,

if ctx.author == ctx.guild.owner

But it doesnt work

formal basin
#

I don’t understand

slate swan
formal basin
slate swan
formal basin
#

Nothing to do with json

glad cradle
glad cradle
slate swan
#

!d discord.ext.commands.hybrid_command

unkempt canyonBOT
#

@discord.ext.commands.hybrid_command(name=..., **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").

A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/master/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command")...
slate swan
#

More accurate - that's the decorator

tough stone
slate swan
#

Do you have a role ID, name or object basically

#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
slate swan
#

Returns a set, just get its length

#

discord.ext.commands.Bot is your bot object

#

commands is the attribute

#

Then just use len() on top of it

#

That doesn't matter

cunning flame
#
def isInt(string):
    try:
        int(string)
    except ValueError:
        await ctx.send("not a number")

async def price(ctx, *args):
    a = ' '.join(args[:-2]) 
    b = int(args[-2])
    c = int(args[-1])
    itemPrice = (b*c)-((b*c)*0.0275)
    embed = discord.Embed(title=f"{a} price", description=f"The price for {a} is {itemPrice} Credits", color=0x4446d1)
    embed.set_footer(text="Created by V.#4181")   
    def isInt(b,c):
        if args[-2] and args[-1] == int:
            await ctx.send(embed=embed)
        else:
            await ctx.send("not a number")
slate swan
#

You have a bot object everywhere

cunning flame
#

the await is out of the async

slate swan
#

Either with just bot. or self.bot.

cunning flame
#

how do I fix

slate swan
exotic maple
# tough stone This should work

Yeah my bad, i accidently put an if statement above that so it reacted to that instead before checking if theyre the guild owner

slate swan
#

And why do you have that function defined twice thinkEgg

cunning flame
#

await ctx.send(embed=embed)
^
SyntaxError: 'await' outside async function

slate swan
#

hi i need help pls help me

#

You haven't turned both in async functions

#

i have a big code so pls dm me

slate swan
slate swan
cunning flame
slate swan
#

ok so i want to ban and kick members in my file

#

The dot?

#

but it doesnt work

cunning flame
#
async def isInt(string):
        try:
            int(string)
        except ValueError:
            await ctx.send("not a number")

async def price(ctx, *args):
    a = ' '.join(args[:-2]) 
    b = int(args[-2])
    c = int(args[-1])
    itemPrice = (b*c)-((b*c)*0.0275)
    embed = discord.Embed(title=f"{a} price", description=f"The price for {a} is {itemPrice} Credits", color=0x4446d1)
    embed.set_footer(text="Created by V.#4181")   
    def isInt(b,c):
        if args[-2] and args[-1] == int:
            await ctx.send(embed=embed)
        else:
            await ctx.send("not a number")

what do I fix here so I won't get:
await ctx.send(embed=embed)
^
SyntaxError: 'await' outside async function

slate swan
#

i have watched 100s of vids and tutorials

#

Then share your code and errors, saying "it doesn't work" doesn't help anyone

slate swan
#

Maybe you want to turn them both into an async function, not just one

cunning flame
#

oh wait

#

wait I realized

slate swan
#

import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
from discord.colour import Colour
from discord import Intents

token = 'MY_TOKEN'
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix='.', intents=Intents.all())

@client.event
async def on_ready():
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name='something SUS'))

@client.command()
@has_permissions(kick_members=True)
async def kick(message, kick_member: discord.Member, *, reason=None):
if kick_member == client.user:
await message.send("You can't kick me! I'm the Valley's watchman! 😠")
elif kick_member.id == 971785723374075924:
await message.send("You can't kick my friend 😠")
elif kick_member == message.author:
await message.send("You can't kick yourself")
elif kick_member.top_role >= message.author.top_role:
await message.send("This person's role is higher or equal to yours!")
else:
await kick_member.kick(reason=reason)
await message.send(f"Kicked {kick_member} for {reason}")

#

@client.command()
@has_permissions(ban_members=True)
async def ban(message, ban_member: discord.Member, *, reason=None):
if ban_member == client.user:
await message.send("You can't ban me! I'm the Valley's watchman! 😠")
elif ban_member.id == 971785723374075924:
await message.send("You can't ban my friend 😠")
elif ban_member == message.author:
await message.send("You can't ban yourself")
elif ban_member.top_role >= message.author.top_role:
await message.send("This person's role is higher or equal to yours!")
else:
await ban_member.ban(reason=reason)
await message.send(f"Banned {ban_member} for {reason}")

@kick.error
async def kick_error(message, error):
if isinstance(error, MissingPermissions):
await message.send("You don't have permission to do that!")

@ban.error
async def ban_error(message, error):
if isinstance(error, MissingPermissions):
await message.send("You dont have permission to do that!")

@client.command()
async def credits(ctx):
myCredits = discord.Embed(title="MrMomo's official bot", color=Colour.dark_red()).set_author(name="MrWick")
myCredits.add_field(name="Made By", value="dumb#5886")
myCredits.add_field(name="Tested On", value="Karma#6031")
await ctx.send(embed=myCredits)

@client.command()
async def unban(ctx, *, member):
bannedUsers = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")

for ban_entry in bannedUsers:
    user = ban_entry.user

    if (user.name, user.discriminator) == (member_name, member_discriminator):
        await ctx.guild.unban(user)
        await ctx.send(f"Unbanned {user.mention}")
        return

client.run(token)

slate swan
#

yea

#

!paste No need to flood chat

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
#

what

#

Looks like some code from a horrible tutorial everyone follows

#

lol

slate swan
#

ok

cunning flame
#
async def isInt(string):
        try:
            int(string)
        except ValueError:
            await ctx.send("not a number")

async def price(ctx, *args):
    a = ' '.join(args[:-2]) 
    b = int(args[-2])
    c = int(args[-1])
    itemPrice = (b*c)-((b*c)*0.0275)
    embed = discord.Embed(title=f"{a} price", description=f"The price for {a} is {itemPrice} Credits", color=0x4446d1)
    embed.set_footer(text="Created by V.#4181")   
async def isInt(b,c):
        if args[-2] and args[-1] == int:
            await ctx.send(embed=embed)
        else:
            await ctx.send("not a number")

it stopped sending messages entirely

#

:d

slate swan
#

Because it's wrongly indented

cunning flame
#

oh?

#

where's the mistake

slate swan
#

Well you never send anything

#

You never send anything in the price function

#

And the isInt function above and below won't work as ctx is not defined in their scope

cunning flame
#

oh

slate swan
cunning flame
#
async def isInt(ctx, *args):
slate swan
# cunning flame ```py async def isInt(string): try: int(string) exce...

just for you information, the code is wrong indented and instead of using an isInt function of yourself, use the isdigit method of the str class, it will return a bool, True when whole of the string is a number, False when the string has numbers with letters/punctuation/unicodes/etc or just False itself when it doesn't have any numbers........

#

The tutorial you're following is known to be bad and a bad way on doing it

slate swan
slate swan
#

You're currently following a tutorial

#

Don't do that

#

Especially not that one

#

but that tutorial worked earlier but idk why its not working now

minor totem
slate swan
slate swan
slate swan
#

coz this is for my friend's server

#

Learn more about the library on the documentation and look for what you need using the search function - if you can't read a documentation we can guide you further with the knowledge you gained

#

are you in that youtuber's server? if yes, do ?tag unban in their bot commands channel

unkempt canyonBOT
#

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

Unbans a user from the guild.

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

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

is what you would use

#

no no

slate swan
#

thats wrong way of doing that.

#

oh

#

Let's imagine a streamer making live (twitch streamer btw) and his live has the title "banana" (for example). Is it possible to do some event that the bot detects that the title of the live has "banana" and puts his twitch channel in a discord specific channel?

slate swan
slate swan
slate swan
slate swan
maiden fable
slate swan
#

i want for ban and kick

#

cuz i tried evrything

#

!d discord.Guild.kick

unkempt canyonBOT
#

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

Kicks a user from the guild.

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

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

!d discord.Guild.ban

unkempt canyonBOT
#

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

Bans a user from the guild.

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

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

lemme see

minor totem
#

@slate swan, I am not up to date. Can you please reiterate what you want to accomplish?

slate swan
#
@bot.command()
async def five(ctx):
    role_ids = [972085371393429514, 972059424594231316]
    rolee = get(ctx.author.roles, id=role_ids)
    if rolee in ctx.author.roles:
        message = await ctx.send("Works")
        time.sleep(3)
        await message.edit(content=f"Check your dms {ctx.author.mention}")
        await ctx.author.send("works")
    else:
        await ctx.send("You do not have access to this command")
#

I cant fix this

slate swan
#

Using the twitch api, yes it's possible - there is eventually an API wrapper

#

i want so if ctx author roles is in role ids run command else send you do not have acces

slate swan
maiden fable
#

u r supplying a list instead of id

#

instead use a for loop and compare each role's id

slate swan
#

You can just use that, see the example

#

!d discord.ext.commands.has_any_role

unkempt canyonBOT
#

@discord.ext.commands.has_any_role(*items)```
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 **any** of the roles specified. This means that if they have
one out of the three roles specified, then this check will return True.

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

So that you can send "You do not have access"

#

i tried await ban(ban_member, reason=reason) this but didnt worked

minor totem
slate swan
#

Need to use on a guild object

#

Such as ctx.guild or message.guild in your case

slate swan
#

not even error comes

#

Or you can just use on the member object - doesn't matter

#

Such as ban_member.ban

slate swan
#

not worked

#

Got any errors?

minor totem
slate swan
#

nope

minor totem
#

It is swallowing all errors

slate swan
#

oh so should i remove

#

coz thats important

#

Or just raise error at the bottom of that function

#

Like

@ban.error
async def ban_error(message, error):
    # Stuff
    raise error
#

after removing ban_error error comes

#

TypeError: ban() missing 1 required positional argument: 'ban_member'

#

And it's not message but it's usually referenced as ctx

#

ok ok

#

lemme see

slate swan
#

Everywhere, but it's just how you wish to name it

#

It's just that to get the actual message you need to do message.message instead of the usual ctx.message

#

It won't fix your code, just a side note

#

no but if i remove it how will i use message.author.top_role

#

You don't remove

#

ok

#

You replace

#

Because that parameter is not a message, it's a context

#

so message.author.top_role will be what if i change to ctx?

#

i know its context

#

ctx.author.top_role 🤷

#

ok lemme see

#

But as I said, won't fix your code

#

Are you actually mentioning a user when executing the command?

#

no

#

Then you might want to do that

#
async def ban(message, ban_member: discord.Member, *, reason=None):
#

await ctx.send(f"Kicked {kick_member} for {reason}") this?

#

Says you need to execute like the following:
.ban @slate swan Reason will be here

#

i do that

#

You just said you didn't

#

i didnt understood what u said but when u showed example i got it

#

Aight aight

#

So, what's your code right now

#

ok wait

#

nvm i fixed it

#

bruh

tribal glacier
#

Sryy

slate swan
#

@slate swan u checking?

#

please help to make sure that the participant has a different balance on different servers

#

sorry i have to go @slate swan pls find me the solution of my problem

#

i really need help

#

i hope someone helps

stray carbon
slate swan
# slate swan sorry i have to go <@456226577798135808> pls find me the solution of my problem

Is your unban command looking like this?

    for ban_entry in banned_users:
         user = ban_entry.banned_users

         if (user.name, user.discriminator) == (member_name, member_discriminator):
             ...

Lucas' unban only works for banning people via their name#discrim, now, this way is not wrong, but there are easier ways of unbanning people, e.g.:

# Unbanning by ID only (converting the ID to a object using discord.Object):
await ctx.guild.unban(discord.Object(id = id))

# converting the given user to a User object by type hinting:
async def unbean(ctx, user : discord.User, reason = None): 
     await ctx.guild.unban(user)

Inspiration from d.py official server

hybrid fjord
#

is this possible yet?

slate swan
#

yea, ofcourse

#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
hybrid fjord
#

ah, thanks

slate swan
#

you would need the development branch of discord.py for that

hybrid fjord
#

?

slate swan
#

you wont get this with pip install discord.py you need to install discord.py using git

hybrid fjord
#

ah

#

@slate swan
File "C:\Python310\lib\site-packages\discord_components\component.py", line 3, in <module> from discord import PartialEmoji, Emoji, InvalidArgument ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Python310\lib\site-packages\ discord\__init__.py)

#

this is just after i installed it

slate swan
#

dont use 3rd party libraries

#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
slate swan
#

!d discord.ext.commands.Bot.commands

unkempt canyonBOT
slate swan
#

use len() on this

hybrid fjord
#

my whole entire code runs off disnake and discord_components, it'll be next to impossible to change them all

slate swan
#

discord_components with disnake????

#

why would you do that.

hybrid fjord
#

wait not disnake

#

just discord_components

slate swan
#

you can either keep using discord_components ( which will never be updated in future ) or use discord.py's components 🙂 not both.

hybrid fjord
#

🤨

#

i'll do it at a later date, it's too much effort to change it all now. how would i uninstall the github? i used the following line:
python -m pip install -U git+https://github.com/Rapptz/discord.py

robust gull
slate swan
#

and you can then install it again

slate swan
jade tartan
#

WARNING: Ignoring invalid distribution -ynacl (c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages) How do i fix this?

slate swan
#

@slate swan help 😔
I'm making buttons with miru but whenever I use the wait method, it never works and listens to any interaction after

@_.command
@lightbulb.command(name="...", description="...", auto_defer=True, ephemeral=True)
@lightbulb.implements(lightbulb.SlashCommand)
async def _foo(ctx: lightbulb.SlashContext):
    view = KickView()
    await ctx.respond("uwu", components=view.build())
    await view.wait()

This is my view

class KickView(miru.View):
    def __init__(self):
        self.confirm = False
        super().__init__(timeout=15, autodefer=True)

    @miru.button(label="Kick", style=hikari.ButtonStyle.SUCCESS)
    async def confirm_kick(self, button: miru.Button, ctx: miru.Context) -> None:
        self.confirm = True
        self.stop()
    
    @miru.button(label="Cancel", style=hikari.ButtonStyle.DANGER)
    async def cancel_kick(self, button: miru.Button, ctx: miru.Context) -> None:
        self.stop()

    async def on_timeout(self):
        self.stop()
unkempt canyonBOT
#

src/extensions/help.py lines 83 to 86

view = HelpButtons(self._bot, context)  # initialising the View class
res = await context.respond(embed=embed, components=view.build())
msg = await res.message()
view.start(msg)```
jade tartan
#

WARNING: Ignoring invalid distribution -ynacl (c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages) How do i fix this? any one

jade tartan
#
WARNING: Ignoring invalid distribution -ynacl (c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ynacl (c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages)
Collecting cogs
  Using cached Cogs-0.4.4.tar.gz (18 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [1 lines of output]
      error in Cogs setup command: use_2to3 is invalid.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
WARNING: Ignoring invalid distribution -ynacl (c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -ynacl (c:\users\thoma\appdata\local\programs\python\python310\lib\site-packages)```
slate swan
#

pip install cogs?

#

why?

jade tartan
#

Should i unisntall python and install it again?

slate swan
jade tartan
#

"

slate swan
jade tartan
slate swan
#

and pass that to msg

slate swan
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to
help group commands together. More information on them can be found on
the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta")
are equally valid here.
slate swan
#

are you importing that cog in ur main file?

ebon island
#

How do I do an on event listener in a cog?

tidal hawk
#

@commands.Cog.listener()

tidal hawk
#

Did you import Image from PIL

slate swan
#

my guess is the file structure is wrong

robust gull
slate swan
robust gull
slate swan
#

Always read the errors before asking :)

crimson compass
#

μπήκαμε μεσά στο τραπ σας δεν μας είδες καν

#

??

tidal hawk
#

what enchanment table language is this

crimson compass
dusky pine
#

greek?

tidal hawk
#

Minecraft?

crimson compass
tidal hawk
#

Does anyone know good existing invitation tracker code?

crimson compass
#

yes

tidal hawk
#

The one I'm using, tends to stop working after a while

crimson compass
#

share the source code

tidal hawk
#

can't find it

crimson compass
tidal hawk
#

okay

#

This one looks promising

slate swan
crimson compass
#

why use github💀

tidal hawk
#

Bruh I've built my own but they wack

#

Building an invitation tracker is pain in the ass

crimson compass
#

share the code

slate swan
#

sort of, i did a project using PIL a few months ago

slate swan
tidal hawk
#

Speak for yourself

slate swan
#

again, from the error it looks like the file structure is wrong, send a screenshot of what it looks like

tidal hawk
#

Ik you can find the inviter by comparing old and new invitations

slate swan
#

And the code above is normal that it stops working after some time

#

Especially when you restart the bot

tidal hawk
tidal hawk
oblique adder
#
text_channel = await interaction.guild.create_text_channel(name=f"ticket-{interaction.user.id}",category=category)
            await text_channel.set_permissions(interaction.user,read_messages = True, send_messages = True,read_message_history = True)
            await text_channel.set_permissions(interaction.guild.default_role, read_messages = False)

how do I use overwrites instead of set_permissions ? I try reading docs but don't really understand please help

slate swan
#

There is an example in the docs

tidal hawk
#

gheez

oblique adder
#

how do I make overwrites for @ everyone ?

slate swan
#

Also in the example

tidal hawk
slate swan
#

I do know because I did it in the past, but sure I don't know :)))))

oblique adder
#

can you help ?

tidal hawk
slate swan
unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission
to create the channel...
oblique adder
#

got it now ty

slate swan
#

That is a horrible way of doing it, as you said. Now think about how else you could do it as there is another method.

slate swan
#

I am, yes

exotic maple
#

Yep you put my bot live today, thanks

slate swan
#

Oh, no problem peepoSheep

slate swan
tidal hawk
#

Okay bro, I was just playing around xD

robust gull
#

@slate swan

slate swan
#

Need code to see where you defined and where you used the msg variable

robust gull
slate swan
#

@slate swan hi

slate swan
#

did u found the problem in my code

slate swan
# robust gull

You need to indent msg = ... one level lower otherwise it won't be defined

#

And you probably want message.content instead

exotic maple
slate swan
#

Oh yeah makes sense

slate swan
#

krypton

robust gull
slate swan
#

Now what is your code and error?

#

my?

slate swan
slate swan
robust gull
slate swan
#

help needed

robust gull
#

@slate swan not trying to be rude but hes kinda trying to help multiple ppl at once so just give him a bit of time

#

@slate swan

slate swan
#

Yeah - also need your code to compare

slate swan
robust gull
crisp drift
#

he has just put a space after any(

slate swan
#

Indentation is still wrong

crisp drift
#

thats not unindent is

robust gull
#

which line

slate swan
#

26

slate swan
slate swan
robust gull
#

what do i have to change

crisp drift
#

Your msg variable assignment

slate swan
#

what wrong im doing

robust gull
crisp drift
#

well let me be specific gimme a sec

slate swan
#

You have

if x:
    # Some stuff
    msg = ....

Needs to be

if x:
    # Some stuff
msg = ....
crisp drift
#

hope thats specific enough

slate swan
# slate swan i dont wanna copy paste but wanna know why my code is not working

according to your code,you take an argument from the user on discord
then, you "split" that argument on each #s ,
the first part being the username, and the second one being the discriminator
then you loop thru all the guild bans and compare the username and discriminators
if any of them matches you unban that user

robust gull
#

ja it works now great

slate swan
#

i wanna know about ban and kick

#

noone can assume what your problem is without your error.

#

i know

#

oh my god this freaking error

robust gull
#

@slate swan what do i need to change if i dont want it to be random

slate swan
#

Yo

#

dont use random.choice then...

robust gull
#

and just delete random choice

slate swan
#

Lol

robust gull
#

or do i type it differently

#

its literally my firs time coding ive never seen a community with such an ego

slate swan
#

??

#

What's the issue

slate swan
robust gull
#

can u answer to the question or do you not want to

slate swan
#

So like

await ....send("Your message here")
slate swan
robust gull
#

sorry i didnt see ur message before typing

#

and do i need to make 3 seperate lines if i want 3 seperate answers

slate swan
#

What do you try to achieve?

robust gull
#

so lets say when i type cat i want the bot to say meow

slate swan
#

Yeah in that case you need a line per trigger (the word, cat) and the reply (meow)

robust gull
#

thank you

slate swan
#

That would be the easy but not elegant way, if you want a better way you could make it more complex but won't be lots of repeating lines - up to you

robust gull
#

the less i have to type the better

slate swan
#

Yeah not sure which one would be easier to understand

robust gull
slate swan
#

Have no tutorials about that, sorry

#

Maybe someone else has one

robust gull
#

can u type the line here or is it too long

slate swan
#

It's a bit too long - I could explain though

robust gull
#

i think i could randomise it with just 1 and repeat it 100 times and it should work

slate swan
#

So basically you would have a JSON-like variable, similar to something like

responses = {
  "cat_reply": {
    "triggers": [
      "cat",
    ],
    "response": "meow"
  }
}

The bot would send meow if any word in the triggers is in the message.
Then in your on_message event, you would iterate over every element in responses , in the example above there is only one.
Then you get the list triggers using .get("triggers") on the element being iterated. This will give you a list of words, similar to mad_words.
After that you can do the same you have now, check if any word in msg is in the list of triggering words and send the message accordingly.
Some pseudo code would be

for response in responses:
  print(responses.get(response).get("triggers")) # List similar to your current 'mad_words' list
  if any(...): # Check if a word is in the message - what you already have
    print(responses.get(response).get("response")) # The response to be sent
#

Hopefully it's understandable, I'm quite bad at explaining - sorry in advance

#

That's basically what I do for my bot

#

pls help me

slate swan
#

ok then dig ur funeral and go inside :)

maiden fable
spring flax
#

When I do [guild.name for guild in self.bot.guilds] it returns [None, None]

maiden fable
spring flax
#

No idea why

#

Ah wait

#

Intents perhaps

maiden fable
#

Intents?

#

Ah yea same thinking

spring flax
#

okay yeah it's intent

visual yarrow
#

@slate swan please don't be rude to people giving help. Here are some tips for getting help:

  • State your question clearly, and make sure to provide enough relevant contextual information.
  • If someone provides advice, please make an attempt to read/understand/apply that advice.
  • If you don't understand the advice given, ask follow up questions, but be specific about what it is you don't understand.
    Thanks.
spring flax
#

i need intents.guild right?

maiden fable
#

!d disnake.Intents.guilds

unkempt canyonBOT
slate swan
#

no one is helping

maiden fable
#

@slate swan we told you the unban command. Lemme reshow u

visual yarrow
maiden fable
#

await ctx.guild.unban(discord.Object(USER_ID_HERE))

slate swan
maiden fable
#

Then?

slate swan
#

ban and kick

spring flax
slate swan
#

i get error

spring flax
#

What's the error?

maiden fable
slate swan
#

lemme tell

maiden fable
#

@spring flax u need intents for bot.guilds too

#

The len(bot.guilds)

slate swan
#

`Ignoring exception in command ban:
Traceback (most recent call last):
File "PATH", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "PATH", line 47, in ban
await ban_member.ban(reason=reason)
File "PATH", line 554, in ban
await self.guild.ban(self, **kwargs)
File "PATH", line 2026, in ban
await self._state.http.ban(user.id, self.id, delete_message_days, reason=reason)
File "PATH", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
File "PATH", line 939, in invoke
await ctx.command.invoke(ctx)
File "PATH", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "PATH", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
`

#

`@client.command()
@has_permissions(kick_members=True)
async def kick(ctx, kick_member: discord.Member, *, reason=None):
if kick_member == client.user:
await ctx.send("You can't kick me! I'm the Valley's watchman! 😠")
elif kick_member.id == Another Bot's ID:
await ctx.send("You can't kick my friend 😠")
elif kick_member == ctx.author:
await ctx.send("You can't kick yourself")
elif kick_member.top_role >= ctx.author.top_role:
await ctx.send("This person's role is higher or equal to yours!")
else:
await kick_member.kick(reason=reason)
await ctx.send(f"Kicked {kick_member} for {reason}")

@client.command()
@has_permissions(ban_members=True)
async def ban(ctx, ban_member: discord.Member, *, reason=None):
if ban_member == client.user:
await ctx.send("You can't ban me! I'm the Valley's watchman! 😠")
elif ban_member.id == Another Bot's ID:
await ctx.send("You can't ban my friend 😠")
elif ban_member == ctx.author:
await ctx.send("You can't ban yourself")
elif ban_member.top_role >= ctx.author.top_role:
await ctx.send("This person's role is higher or equal to yours!")
else:
await ban_member.ban(reason=reason)

`

#

your bot is missing the required permissions to ban/kick users

#

or you're trying to ban/kick a user higher in hierarchy than the bot

#

oh

#

im trying to ban a normla user

#

with normal permission

visual yarrow
#

Could you use a code blocks please. That's:
```python
your code here
```

#

It's a bit easier to read.

slate swan
#

so you're sure your bot has a role with those permissions?

#
  • make sure the user's top role is below bot's top role
  • bot has kick/ban member Permission
  • the user you're trying to kick is not the owner
#

Who can help me with a code?

visual yarrow
ebon island
#

What is the proper way to mute a Member object in a VC? Possibly Server Mute so the user cannot unmute

#

I changed suppress value to True to test, not sure if that is good or bad practice but can't test until I get a friend on to test

#

since I am admin of the server

slate swan
#

!d discord.Member.edit

unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
slate swan
#

and mute works on server admins too fyi

ebon island
#

ooh cool, so I'd do member.edit(mute=True) as an example

#

dope let me try

slate swan
#

yea, that would work

ebon island
#

it is muting the bot rather than the user 😛

#

close though!

#

also, is there a way to see the type of on_voice_state_update event it is? So only reacting for certain events?

stray carbon
#
class Elegant(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or('='), intents=nextcord.Intents.all())
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(KarutaView())
            self.add_view(QuickRoles())
            self.add_view(OwOView())
            self.add_view(Access())
            self.add_view(SelfRoles())
            self.add_view(PingRolesOne())
            self.add_view(PingRolesTwo())
            self.add_view(PingRolesThree())
            self.add_view(ColorRolesOne())
            self.add_view(ColorRolesTwo())
            self.add_view(Verify())
            self.persistent_views_added = True
        setattr(self, "owodb", await aiosqlite.connect("owo.db"))
        async with self.owodb.cursor as cursor:
            await cursor.execute('CREATE TABLE IF NOT EXISTS owotimes (user INTEGER, times INTEGER)')
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        while True:
            statusType = random.randint(0, 1)
            if statusType == 0:
                 await self.change_presence(status=nextcord.Status.idle, activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"{len(set(self.get_all_members()))} users"))
            else:
                await self.change_presence(status=nextcord.Status.idle, activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"{len(set(self.get_all_members()))} users"))
            await asyncio.sleep(600)
Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Akai\AppData\Local\Programs\Python\Python38\lib\site-packages\nextcord\client.py", line 417, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Akai\Desktop\New folder\eleg.py", line 33, in on_ready
    async with self.owodb.cursor as cursor:
AttributeError: __aexit__
#

oh cursor()

#

nvm mb

robust niche
#

is there any site except for pastebin that can store text data and be read by python?

stray carbon
#
    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot:
            return
        if "owo" in message.content:
            async with self.bot.owodb.cursor() as cursor:
                await cursor.execute('SELECT times FROM owotimes WHERE user = ?', (message.author.id,))
                data = await cursor.fetchone()
                if data:
                    await cursor.execute('UPDATE owotimes SET times = times+1 WHERE user = ?', (message.author.id,))
                else:
                    await cursor.execute('INSERT INTO owotimes (user, times) VALUES (?, ?)', (message.author.id , 1,))
            await self.bot.owodb.commit()

is there any way to set cd to this

exotic maple
#

How do i do or the user is the guild owner?

#

Why wont this work?

ivory cave
#

@stray carbon thats an interesting about me xd

ivory cave
slate swan
#

a useless init with a coroutine inside it

ivory cave
#

why is there a .init() thats empty

sick birch
#

guys it's an about me. no need to perform an analysis on every character of it

slate swan
#

guys you dont need an init if your class wont take any arguments!

ivory cave
ivory cave
#

im not hating xd, im just confused a bit bc yk, its code

sick birch
#

no need for a 4 page doctoral thesis on someone's about me

slate swan
#

let me check your about me robin😳

ivory cave
slate swan
#

you forgot periods in your sentences robinpithink

ivory cave
#

this dude 💀

#

poor robin hugs

slate swan
#

that about me is worse than your dpy examples

#

😭

sick birch
#

sad

ivory cave
#

let me check ur about me self.okimii

slate swan
#

😳

ivory cave
slate swan
#

thats a big about me

ivory cave
#

hugee

slate swan
ivory cave
#

no nitro lemon_angrysad

slate swan
#

kek

ivory cave
#

bro i love communities with ppl who code, its like im talkin to brothers 🙏

#

taking this quite too literally

slate swan
#

yup

ivory cave
#

imma go

class Toilet:
    def pee():
        return "pee"
print(Toilet.pee())
slate swan
#

that isnt a classmethod bro

#

😭

pliant gulch
#

It's the person that does

slate swan
#

😭

sick birch
#

what a strange conversation i'm witnessing

slate swan
#

😳

pliant gulch
#

Unless the toilet has a bidet

ebon island
#

How do I handle awaiting a response from a user in DMS with the bot?

#

since no ctx and all like normal wait_for

#

and no channel

pliant gulch
#

Have a check that checks if message.guild is None

slate swan
sick birch
#

Or if message.channel is DMChannel if you find that helps you understand it better

ebon island
#

nah not message.guild is fine, where would that be? In my check function?

sick birch
#

yup

pliant gulch
slate swan
#

Use deco if u want it to work in dm

#

how

ebon island
#

really that is slower?

#

I'd think it just evaluates boolean

sick birch
#

barely slower

ebon island
#

so I don't know why it'd be slower

slate swan
#

andy youre scary just like arl

sick birch
#

There are a lot of little things in python that are barely slower or barely faster

slate swan
#

you guys are both scary smart at python

sick birch
#

You can be the judge of if you care or not

ebon island
#

I think for a discord bot it probably doesn't matter too much but good to know

pliant gulch
#

is checks the ID of the objects you are comparing. If you just do if something it has to do multiple checks

slate swan
#

..

#

right is is faster because its a hash lookup

ivory cave
pliant gulch
#

?

#

It's not a hash lookup

slate swan
#

but you said ids😭

pliant gulch
#

!e ```py
print(id("foo"))

slate swan
#

oh

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

140335024824944
slate swan
#

the memory allocation

#

🗿

slate swan
ivory cave
#

lmfao

slate swan
#

right its a static method i didnt see the argument's

dull terrace
slate swan
#

😭

dull terrace
slate swan
dull terrace
slate swan
dull terrace
slate swan
#

fetchone

dull terrace
#

is it because of the slicing?

paper sluice
#

ya

#

(await cur..)[0]

slate swan
#

thats weird tho

paper sluice
#

?

dull terrace
#

okay thanks... gotta update a few to do that ablobsweats

slate swan
#

wouldn't that raise coroutine object cant be index or something like that

paper sluice
#

time to check out cpython

pliant gulch
#

Man I hate looking for stuff in the cpython repo, github fuzzy searching makes it such a task to find specific internals

#

I'd have more luck searching for the comments directly instead of names

prisma forge
paper sluice
paper sluice
maiden fable
prisma forge
#

I opened a help channle

maiden fable
#

which

prisma forge
pliant gulch
#

Not sure how async will work, will prob need to strictly run off event loop

paper sluice
#

cython discord wrapper 👀 , sound cool ngl

glad cradle