#discord-bots

1 messages Β· Page 751 of 1

unkempt canyonBOT
#

class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.

The following implement this ABC...
twin moon
#

GuildChannel is the type of channel which is in interaction.channel

maiden fable
#

Yea, so?

#

Ah wait

#

!d discord.abc.GuildChannel.permissions_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
maiden fable
#

Yea this exists

twin moon
maiden fable
twin moon
unkempt canyonBOT
#

property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
twin moon
#

bruh?

#

there is no

#

interaction.guild.permissions_for

#

!d discord.abc.GuildChannel.permissions_for

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
maiden fable
#

No

#

!d discord.Role.permissions

unkempt canyonBOT
twin moon
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

slate swan
#

is Music imported in __init__.py

maiden fable
#

None will spoonfeed

twin moon
#

on_message:
level + 1

twin moon
#

use a db

#

like sqlite

static lintel
slate swan
twin moon
slate swan
slate swan
#

Or is it same as the old one

static lintel
#

its the same as the old one

twin moon
#

AttributeError: 'ClientUser' object has no attribute '_roles'

slate swan
#

it's guild.me.roles

twin moon
#
@nextcord.slash_command(name = "kick",description="kick a member",guild_ids=[ServerID])
async def kick(self,interaction:nextcord.Interaction,member:nextcord.Member=None,*,reason:str = SlashOption(default = "no reason provided",required = False)):
    await interaction.response.defer()
    if interaction.channel.permissions_for(interaction.user).kick_members is True and interaction.channel.permissions_for(self.client.user).kick_members is True:
        if member is None:
            return
        await member.kick(reason=reason)
        embed = nextcord.Embed(description=f"{interaction.user.mention} kicked {member}")
        await interaction.followup.send(embed = embed)```
#

@slate swan Learn python

#

not plagarism

#

if we dont help you its because you copied

twin moon
#

I want the perms

maiden fable
twin moon
#

or him

maiden fable
#

Typo

slate swan
# twin moon why?

Because a user does not have perms , but a member does , and Guild.me returns the bot's member object for the Guild object

#

/roles

slate swan
#

no

maiden fable
#

!d discord.Interaction.user

unkempt canyonBOT
maiden fable
#

It can be both

slate swan
#

Yep

#

And I'm not asking you to use that for inter.user , you have self.client.user there , that's what I'm talking about

slate swan
#

told you twice

twin moon
twin moon
slate swan
#

No

twin moon
twin moon
#
if interaction.channel.permissions_for(self.client.user).mute_members is True:```

```roles = obj._roles
AttributeError: 'ClientUser' object has no attribute '_roles'```
visual island
#

use guild.me for it

twin moon
visual island
#

how what?

unkempt canyonBOT
#

property me: discord.member.Member```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
twin moon
visual island
#

replace the self.client.user with guild.me

twin moon
visual island
#

yeah

placid skiff
twin moon
placid skiff
#

Wait what module are you using? Lol

twin moon
placid skiff
#

Bruh just use disnake, checks works for slash commands too

placid skiff
#

Lol

twin moon
#

nextcord is official

placid skiff
#

tbh is a fork

twin moon
#

and official not like pycord

placid skiff
#

Bruh disnake is a fork too, it has literally the same thing that has nextcord but slash commands are better

placid skiff
#

It isn't official πŸ˜‚ πŸ˜‚

twin moon
quick gust
#

What does "official" mean to you?

placid skiff
#

discord.py was official, then they stopped mantain it and people started use forks, there are planty of them and nextcord isn't official

placid skiff
#

No it isn't πŸ˜‚ πŸ˜‚
There isn't a best fork, they're all the same for the most of things, in disnake you can use slash commands with check both custom and built-in from the fork, disnake started used slash commands a lot before then nextcord and they're not in test phase anymore, they works fine

twin moon
placid skiff
#

Bro literally, what part of "they're all the same" you didn't understand?

slate swan
#

there's no "bigger" fork existing , but if you're talking about features
Disnake is surely ahead others

twin moon
#
TypeError: Timeout must be a `datetime.datetime` or `datetime.timedelta`not _MissingSentinel```
#
@nextcord.slash_command(name = "nickname",description="kick a member",guild_ids=[ServerID])
    async def nickname(self,interaction:nextcord.Interaction,member:nextcord.Member = None,*,nickname:str = SlashOption(default = None,required = False)):
        await interaction.response.defer()
        if interaction.channel.permissions_for(interaction.user).manage_nicknames is True and interaction.channel.permissions_for(interaction.guild.me).manage_nicknames is True:
            await member.edit(nick=nickname)
            await interaction.followup.send(f"{member} nickname has been changed to {member if nickname is None else nickname}")```
slate swan
#

It takes a datetime object

#

and there's not timeout there , wrong code?

twin moon
#

nick (Optional[str]) – The member’s new nickname. Use None to remove the nickname.

slate swan
#

.... The error comes from somewhere you have Timeout

twin moon
# slate swan .... The error comes from somewhere you have Timeout
  File "c:\Users\Kinder\Visual Code\PY Bot Moderation\cogs\moderation_slash_command.py", line 116, in nickname
    await member.edit(nick=nickname)
  File "C:\Users\Kinder\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\member.py", line 795, in edit
    raise TypeError(
TypeError: Timeout must be a `datetime.datetime` or `datetime.timedelta`not _MissingSentinel
Ignoring exception in on_interaction```
slate swan
#

Oh this , someone else faced this but was unable to solve , did you try asking this in their support server?

timid wagon
#

I think that's a bug? You're not passing any kind of timeout attribute

slate swan
#

hm , I'll ask and let you know

twin moon
slate swan
#

@twin moon try this member.edit(nick=nickname , timeout= member.timeout)

#

How can I host bot

twin moon
twin moon
slate swan
#

your bot misses permission to edit nickname of that member

slate swan
slate swan
#

Raspberry Pi and self host are always an option

slate swan
#

Edit your nick

slate swan
twin moon
slate swan
#

I don't know how to do that

slate swan
twin moon
slate swan
#

How do you expect someone to edit you name

maiden fable
#

no one can touch the Owner

twin moon
green bluff
maiden fable
#

Should work

green bluff
#

doesnt tho

#

saved and reset

maiden fable
#

Error

green bluff
#

nup

#

nothing'

slate swan
#

It can't run ?

twin moon
maiden fable
#

Do u have intents? @green bluff

quick gust
#

You are the server owner and the bot cannot ban, kick, mute, timeout or edit your nickname

maiden fable
#

For the owner

quick gust
#

Remove/add his roles?

maiden fable
#

Yea

quick gust
#

Oh

maiden fable
#

As long as the role is lower than the bot's highest role

quick gust
#

I see

copper gulch
#

is there a way to get a list of user_ids in a certain voice_channel they joined in

maiden fable
unkempt canyonBOT
copper gulch
#

ok ok thank you

spring flax
#

hey if I wanted to make a modmail bot, what do you think is the best way to log conversations?

spring flax
slender pumice
#

yeah

#

on_message and save the messages in a txt file for example

#

but u need to implement some checks to not interfere with other dms/channels/servers

leaden hollow
#

    @commands.command(description='')
    @commands.cooldown(1,z, commands.BucketType.user)
    async def spin(self, ctx):
        fs = rnga()

so I want same value as fs in cooldown,any way it is possible?

slender pumice
#

how what

solar anchor
#

is there any free way to run my bot 24/7?

slender pumice
solar anchor
#

is that free?

slender pumice
#

Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
https://www.time4vps.eu/ Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.

Linode

Our mission is to accelerate innovation by making cloud computing simple, affordable, and accessible to all.

Vultr

Vultr Global Cloud Hosting - Brilliantly Fast SSD VPS Cloud Servers. 100% KVM Virtualization

slender pumice
#

u can do that, first u need to check if the messages are in dms then u respond depending on how u wanna implement command listening for dms

#

in probot's case, in dms, it doesnt need prefix for commands

#

dms as in direct messages

heavy folio
#

what do younot understans

boreal ravine
#

dms = your messages with someone

solar anchor
#

lol what

tough lance
#

Hi.

obsidian ledge
#

how many buttons can you put on a single message

heavy folio
#

25 i think

obsidian ledge
#

alr

maiden fable
#

!d discord.ext.commands.dynamic_cooldown @leaden hollow

unkempt canyonBOT
#

@discord.ext.commands.dynamic_cooldown(cooldown, type=BucketType.default)```
A decorator that adds a dynamic cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

This differs from [`cooldown()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.cooldown "discord.ext.commands.cooldown") in that it takes a function that accepts a single parameter of type [`discord.Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") and must return a [`Cooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Cooldown "discord.ext.commands.Cooldown") or `None`. If `None` is returned then that cooldown is effectively bypassed.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.

New in version 2.0.
slate swan
#

Is there an alternative to guild.me.guild_permissions.send_messages for a specific channel?

#

make a function to convert it

heavy folio
#

what isnt working

#

what isnf working

slate swan
#

hm?

slender pumice
#

whats the problem?

#

getting any errors? send them here

slate swan
#

Im trying to get attachments from a message object, but it returns this error, and its vague to me.

InvalidDocument: cannot encode object```

code:
```py
        image = await self.bot.wait_for('message', check=message_check(channel=ctx.author.dm_channel))
        link = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',image.content)
        if not link:
            raw_link = image.attachments[0].url
        else:
            raw_link = image.content```
#

what's the message_check variable

#

/function

#

which app can i use to host bots

slate swan
#

but thats not the issue

vale wing
#

What's the best way to fetch the full error traceback into string in on_command_error

slim ibex
#

you can make it send the error it self

#

EX:

async def on_command_error(context, error):
  if isinstance(error, MissingRequiredArgument):
    await context.send(error)
#
@staticmethod
async def error_embed(error) -> Embed:
  eEmbed = Embed(title=f"{error}", color=0xFF0000)
  return eEmbed

@classmethod
async def _on_command_error(cls, context, error) -> error_embed:
  if isinstance(error, commands.MissingRequiredArgument):
    eEmbed = await cls.error_embed(
       error
    )
    await context.send(embed=eEmbed)

In my case, I use an embed that actually shows the traceback/error in the same way

vale wing
#

@slim ibex I asked about traceback with a reason

rapid walrus
#

guys

#

im planning to make a card game
every turn the bot will wait for message from 2 player
if 2 player finish chosing their cards, then next turn will continue
i know there is a way to wait for a message but idk how to make it continue only if both 2 player sent a message (and there will be a timeout also)

vale wing
#

Wait for one then wait for another?

rapid walrus
vale wing
#

At the same time?

rapid walrus
#

😐

vale wing
#

You will have to wait_for twice anyway

rapid walrus
#

if just 1 person choose and the other don't it wont continue until both chose

vale wing
#

If you are waiting for message

rapid walrus
vale wing
#

Just call it twice and get 2 results lol?

rapid walrus
#

? wdym

rapid walrus
#

uhm the invite?

#

ok wait

vale wing
#
player1: discord.User
player2: discord.User
#just typedef don't mind

await ctx.send(f'{player1.mention} choose your card')
m1 = await bot.wait_for('on_message', check=lambda m: m.author.id == player1.id)
await ctx.send(f'{player2.mention} choose your card')
m2 = await bot.wait_for('on_message', check=lambda m: m.author.id == player2.id)```
@rapid walrus isn't this what you need
rapid walrus
vale wing
#

Why and were there any errors

#

!code

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.

rapid walrus
#

cuz it will wait for m1 first until m1 is sent, but not m2, if m2 send first, it won't do anything

vale wing
rapid walrus
#

` not ' maybe

vale wing
#

Then make the check be like

lambda m: m.author.id in (player1.id, player2.id)```
And handle it properly
#

You didn't add py at the start that's why

vale wing
#

That's for the first

rapid walrus
#

i will try, thank you

vale wing
#

For the second you gotta wait for the one who didn't respond

vale wing
#

πŸ‘

rapid walrus
#

lol πŸ™‚

#

lol :V

vale wing
#

Almost no time but what the issue is

#

Sorry gtg DM me so I can help you later or wait for another person to come

slate swan
#

My embeds are always so squashed, is there a command that sets my embed to maximum size?

#

not that I know of, no. discord embeds are automatically sized to fit content.

#

may you show an example of what "squashed" means?

rapid walrus
glad thicket
#

Hey can anyone help me

#

How do I read messages after the command is intieated(inside a COG)

#

Like if I put the command &cog and the question comes I want to give 30 secs to answer

#

How do I read the messages

#

ok πŸ˜”

#

Can anybody else help me

spring flax
unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
glad thicket
slate swan
#

How do i delete channel overrides for user that are independently added to the overrides?

#

You can edit the override for user as None

surreal thistle
#

How do I check if a message exists in a channel?

dire folio
#

Wdym

surreal thistle
#

I want to check if a message was deleted or still exists.

final iron
surreal thistle
#

I solved the problem... Thank you

rapid walrus
terse fossil
#

!d import

unkempt canyonBOT
#

7.11. The import statement


import_stmt     ::=  "import" module ["as" identifier] ("," module ["as" identifier])*
                     | "from" relative_module "import" identifier ["as" identifier]
                     ("," identifier ["as" identifier])*
                     | "from" relative_module "import" "(" identifier ["as" identifier]
                     ("," identifier ["as" identifier])* [","] ")"
                     | "from" relative_module "import" "*"
module          ::=  (identifier ".")* identifier
relative_module ::=  "."* module | "."+
```...
terse fossil
#

how do i import this new discord in python?

slate swan
rapid walrus
slate swan
rapid walrus
terse fossil
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

rapid walrus
#

sus

#

:V

slate swan
rapid walrus
spring flax
#

Nope

manic wing
#

essentially

#

!pypi disnake || use this

unkempt canyonBOT
slate swan
#

it's no longer.maintained

#

Not like it won't work

#

hey

#

how to run a bot and a flask file together?

#

sarthak

#

can u help me?

#

why would you want to do that, exactly?

slate swan
#

on my flask website

#
import discord
from discord.ext import commands, ipc
from flask import Flask, render_template, request, session, redirect, url_for
from discord.ext import ipc
import subprocess
import time


class MyBot(commands.Bot):

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        self.ipc = ipc.Server(self,secret_key = "a")

    async def on_ready(self):
        """Called upon the READY event"""
        print(f"Connected as {my_bot.user}")

    async def on_ipc_ready(self):
        """Called upon the IPC Server being ready"""
        print("Ipc server is ready.")

    async def on_ipc_error(self, endpoint, error):
        """Called upon an error being raised within an IPC route"""
        print(endpoint, "raised", error)
intents = discord.Intents().default()
my_bot = MyBot(command_prefix="!", intents=intents)

@my_bot.ipc.route()
async def get_guild_count(data):
    return  len(my_bot.guilds)  # get the guild object using parsed guild_id

   

  

my_bot.ipc.start()```
#
from flask import Flask, render_template, request, session, redirect, url_for
from discord.ext import ipc
import os
from subprocess import *

import time
app = Flask(__name__)
ipc_client = ipc.Client(secret_key="a")

@app.route("/")  
def home(): 
  guild_count =  ipc_client.request("get_guild_count")
  
  return  render_template("index.html", content=guild_count)


if __name__ == "__main__":
    
    app.run()   ```
devout iris
#

hey, how can i make changing statusses??? i.e. it will be changed every 5 seconds... etc.

dire folio
#

^

devout iris
#

where are docs?

dire folio
#

Do you know what a ratelimit is?

manic wing
#

ratelimits are left ambiguous so people dont go push the limits

devout iris
manic wing
#

they also scale, therefore apply separately to each person

#

called dynamic ratelimiting

devout iris
#

is this cooldown?

#

or different

dire folio
#

It's different to a cool down

devout iris
#

ah alr i'm googling

dire folio
#

@devout iris

devout iris
#

ah tysm

final iron
#

Can somebody send the discord page on the developer privacy policy?

slate swan
pallid cobalt
#

idk anything about coding but i want to make a bot that records every message in a specified channel and instantly deletes it since i cant find one that exists already; can anybody help me scripting that?

final iron
#

It's far from a beginner project

karmic lintel
#

something like that

#

idk exactly cuz i am new too

#

webhook for me = ❌ ..... lol sorry i can't help... btw good luck

severe field
#

How to give role to user by server id and user id?

surreal sierra
#

I just got a quick question, if you are not supposed to use discord.py bcz its dead then what are u supposed to use?

maiden fable
#

U can send a max of 120 requests every min, so about two requests in a second before getting ratelimited... I don't really think he is gonna get rateimited, provided, he isn't doing much ws intensive work

dire folio
surreal sierra
dire folio
#

replace every discord with disnake and it should work

surreal sierra
#

okay, thanks!

devout iris
#

how to connect and disconnect to voice channels?

slate swan
#

so you don't really need to replace anything

#

it should work OOTB

final iron
unkempt canyonBOT
#

await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.

This requires [`Intents.voice_states`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
final iron
#

And

#

Actually I have no idea how to disconnect

maiden fable
unkempt canyonBOT
#

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

Disconnects this voice client from voice.
maiden fable
#

@devout iris ^^^

tiny ibex
#

How to check if the user has permissions to view a channel?

slate swan
#

oh , a user

tiny ibex
slate swan
#

!d discord.TextChannel.permissions_for you can get perms on user using this

unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
tiny ibex
#

Tysm

slender pumice
#

maybe ur error handler is silencing the errors

#

k

slate swan
#

using @bot.command() async def move(ctx): await ctx.send('hui') should create a command and with the prefix bot = commands.Bot(command_prefix='$') $ i should be able to run it like $move, right?
bc for some reason it isnt working

#

nvm im wrong

slender pumice
#

these might help

maiden fable
#

The bot won't know in which guild u want the perms from

jade bay
#

How do I use an older version of dpy?

dire folio
#

Why would u want to do that

jade bay
honest shoal
jade bay
honest shoal
#

the version which u want to use

#

pip install discord.py==1.7.3

jade bay
#

and now whenever I run my python file, it will use this version of dpy?

dire folio
#

Ye

elder pike
#

My bot just goes offline after like a minute after launching it could someone please look at my code?

#

Fixed it by using await asyncio.sleep() function

potent spear
#
  1. you haven't even stated your problem
  2. you can perfectly do admin_role = guild.get_role(id)
normal jasper
#

guys im trying to make a leader board for my economy but when i use the command i get this :

normal jasper
# normal jasper guys im trying to make a leader board for my economy but when i use the command ...
@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
    users = await get_bank_data()
    leader_board = {}
    total = []
    for user in users:
        name = int(user)
        total_amount = users[user]["wallet"] + users[user]["bank"]
        leader_board[total_amount] = name
        total.append(total_amount)

    total = sorted(total,reverse=True)    

    em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = random.randrange(0, 0xffffff))
    index = 1
    for amt in total:
        id_ = leader_board[amt]
        member = client.get_user(id_)
        name = member.name
        em.add_field(name = f"{index}. {name}" , value = f"{amt}",  inline = False)
        if index == x:
            break
        else:
            index += 1
    em.set_footer(icon_url = ctx.author.avatar_url,text =f"Requested By {ctx.author}")
    await ctx.send(embed = em)

native wedge
flat solstice
#

okay my self.config.test_accounts is a list of user ID's, is this correct for checking if the member.id is in that list? (This fires on member joins and removes

#

i don't think != is what I want bc that's not equal to but i just kind seem to remember what it should be

potent spear
potent spear
flat solstice
leaden hollow
#

so I'm making a command which generates a random number x
then the commands waits for x seconds and sends the reply
I need to add a timeout for that x seconds so commands can't be stacked by the same user,no idea how to implement that

potent spear
#

it's a decorator

devout iris
#

Is there anything we can distinguish whether the person joining the server is a bot or a user?

leaden hollow
#

I know how to work with cooldowns decorator

devout iris
#

Ah thx :)

potent spear
leaden hollow
#

yes

native wedge
#

how do i make certain commands make it available to users who only have certain permissions?

leaden hollow
native wedge
potent spear
potent spear
frank tartan
#

how can i make a command that shows me all the members in a sertain role?

potent spear
potent spear
frank tartan
potent spear
#

then you can do role.members to get all the members of that role

#

async def give_role_members(ctx, role: discord.Role):

leaden hollow
frank tartan
potent spear
potent spear
leaden hollow
#

that's the main thing

potent spear
leaden hollow
#
commands.group(description='',invoke_without_command=True)
    @commands.cooldown(1,z, commands.BucketType.user)
    async def test(self, ctx):
        z = rand()
        await ctx.send(whatever)
        await asyncio.sleep(z)
        await ctx.send(f"Stopped at {z}sec")```
#

this is my current code

potent spear
#

I said max_concurrency

frank tartan
frank tartan
potent spear
#

you can just do ctx.guild...

#

no need for the member

#

unless it's in an event, then you don't have ctx

limpid thicket
#

So simple yet so confusing..

checkEmbed = discord.Embed(description="**Searching** for username...", color=green)
checkEmbed.set_footer(text=f"Command executed by β€’ {author.name}")
checkMsg = await ctx.send(embed=checkEmbed)
```Error I'm getting is:

ret = await coro(*args, **kwargs)
15.01 13:52:05 [Bot] File "/bot.py", line 1330, in discord
15.01 13:52:05 [Bot] checkEmbed = discord.Embed(description="Searching for username...", color=green)
15.01 13:52:05 [Bot] AttributeError: 'Command' object has no attribute 'Embed'

potent spear
#

check your imports

frank tartan
# potent spear you can just do `ctx.guild`...

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'member' is not defined

role = discord.utils.get(member.guild.role.members, name=roleName)
potent spear
frank tartan
limpid thicket
potent spear
frank tartan
potent spear
potent spear
frank tartan
slender pumice
#

what r u trying to do

limpid thicket
#

Can I just finish this, 1 moment.

limpid thicket
potent spear
#

he doesn't understand the concept of typehinting which will convert the argument to a role object...
instead of "manually converting" it

frank tartan
leaden hollow
limpid thicket
#

And you want to display all the members who have a specific role yes?

frank tartan
potent spear
#

so let's say πŸ˜„ is equal to roleA or what?

frank tartan
potent spear
#

yup, and staff is the name of your role

#

command would look like

#

async def members(ctx, role: discord.Role):

harsh stump
#

Hi, how do i start programming bots? I was thinking I want to do smth with apis

frank tartan
flat solstice
#

So I have this colour of deepskyblue 00bfff but my embeds don't seem to like the code, anyone able to tell me why

slender pumice
#

then what

frank tartan
native wedge
#

i made my bot so it replies to messages with a certain word in em, how do i make the bot react to the message with the provided word? message.react?

potent spear
slender pumice
harsh stump
slender pumice
#

the role arg can be name or id in this case

frank tartan
potent spear
#

they contain examples etc

flat solstice
#

@slender pumice and @limpid thicket thanks for the help πŸ‘

slender pumice
#

np

#

@frank tartan what r u trying to do

#

i just joined the chat so can u explain it to me

frank tartan
cloud dawn
slender pumice
#

then why dont u wanna use role: discord.Role

frank tartan
limpid thicket
#

discord.Role can be passed as a mention, id, or name so use the method which the users in the chat are providing (discord.Role parameter in command)

spring flax
#

what do you think is the best way to make a modmail bot? Like through a DM channel, a thread, or through a channel

limpid thicket
#

You asked for the name, so it should work.

frank tartan
cloud dawn
frank tartan
cloud dawn
#

Do recommend some kind of line paginator like the Python bot

vale wing
#

How to get full error traceback into the string in on_command_error (and notice I am not asking to explain me the error handler or how to raise an error, alr know that)

vale wing
#

How to get its traceback

#

Into the string

#

Without raising it

frank tartan
slender pumice
#

then whats the problem with

async def members(ctx, role: discord.Role):
  embed = discord.Embed(title="title", description = "description")
  for member in role.members:
    #do stuff maybe add them to a list or add them as an embed field
  await ctx.send(embed=embed)```
cloud dawn
#

See what is in it.

vale wing
#

Ok

limpid thicket
#

End of conversation lol?

@client.command()
async def hasrole(ctx, role: discord.Role = None):
  if role is None:
    await ctx.send("Please specify a role.")
  else:
    if len(role.members) < 1:
      await ctx.send("There are no members with this role.")
    else:
      memberslist = ""
      for member in role.members:
        memberslist += f"- {member.name}#{member.discriminator}\n"
      await ctx.send(f"Members with this role:\n\n{memberslist}")

@hasrole.error()
async def hasrole_error(ctx: commands.Context, error: commands.CommandError):
  if isinstance(error, commands.RoleNotFound):
    await ctx.send("Role not found.")
slender pumice
cloud dawn
#

πŸ˜‚

flat solstice
#

If I want my bot to mention a category do I need to call get_category or get_channel?

native wedge
#

how do i make a bot react to a message?

cloud dawn
unkempt canyonBOT
#

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

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

Warning

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

@cloud dawn got these

limpid thicket
#

Parameter is the emoji.

vale wing
#

Seems like __traceback__ is empty

cloud dawn
vale wing
#

It is None

flat solstice
# cloud dawn .mention

oh yeah ik i'd need to .mention to mention it but first I need it to be a category object (I think that's the right term)

native wedge
vale wing
#

There must be a way to get it

cloud dawn
#

Discord will format that into a mention

vale wing
#

It is most likely fetched with external library

flat solstice
#

true, but don't mentions like that visually break somtimes?

cloud dawn
cloud dawn
flat solstice
#

well it will be in a embed, but I'll do this for now. if I find a different way i'll try it then

cloud dawn
#
try:
    raise error
except Exception as e:
    await ctx.send(e)
frank tartan
vale wing
#

There's no point in this "trick", it is just raising an exception and catching itself lol

native wedge
#

ok i made my bot react with normal emojis, how do i use custom emojis?

spring flax
#

Dropdown menus don't have default timeout right

vale wing
cloud dawn
vale wing
#

I actually just need it to send the traceback to a private channel, but I need traceback and not the handler, people suggested me the handlers today lmao

cloud dawn
#

Well it's better to handle them rather than just sending a traceback. I use the logging module if something serious goes down.

vale wing
#

Handler is for users, traceback is for developers

#

As of my logic

cloud dawn
#

I just have a log and if it isn't serious i got my console.

native wedge
vale wing
#

I have the handler for users and it works fine, but I am too lazy to connect to the VPS

cloud dawn
vale wing
#

I have the commands for bot to automatically update without me needing to connect to the server and execute commands, so I want to send it tracebacks to the private channels so I don't have to open VPS at all HAHA

cloud dawn
vale wing
#

We never get fatal crashes (doesn't mean we can't but the chance is really low)

cloud dawn
#

But never 0 πŸ˜›

vale wing
#

Btw about chances

#

I made a function for like "chances selection", but it is sometimes smoking grass and returning None, I wonder what have I missed in it

fading dirge
#

does anyone know how can I make embed message with this reactions?

native wedge
#

my bot doesnt work anymore it says i made too many api requests

native wedge
vale wing
#

Forgor

#

!e

from typing import Any
from random import randint

def choice(objects: dict) -> Any:
    range_dict = {}
    current_point = 0
    last_number = 0
    last_item = list(objects.keys())[-1]
    for item in objects:
        next_point = current_point
        if last_item != item:
            next_point += int(objects[item] * 10)
        else:
            last_number = next_point = next_point + int(objects[item] * 10) + 1
        
        range_dict[range(current_point, next_point)] = item
        current_point = next_point

    num = randint(0, last_number)
    for i in range_dict:
        if num in i:
            return range_dict[i]

for _ in range(5):
    print(choice({'bruh': 70, 'no': 30}))```
unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

001 | bruh
002 | bruh
003 | no
004 | bruh
005 | no
vale wing
#

Works fine but sometimes this returns None

#

What could be a reason for this

vale wing
#

Somewhere in a bad place*

native wedge
vale wing
upbeat otter
#

welp

vale wing
native wedge
#

@vale wing

vale wing
#

Oh no

#

Don't do commands like this for god's sake

upbeat otter
#

freecodecamp-

vale wing
#

There's a decorator

native wedge
vale wing
#

!d discord.ext.commands.Bot.command simpliest implementation

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
upbeat otter
#

and use discord.ext.commands.Bot instead of discord.Client

vale wing
#
@bot.command()
async def somenicecommand(ctx):
    await ctx.send(f'Hi')```
native wedge
#

ohh i understand why i got api blocked

#

its cause the event is looking like every second for commands thats why?

vale wing
#

Nope

#

The event is something about websockets and gateway, dunno about that very much

#

But actually discord sends the events to you

native wedge
#

i dont know what guides are good or bad sorry

vale wing
#

Very good even after maintenance end

pliant gulch
#
@client.collect(rin.Event.GUILD_MEMBER_JOIN, amount=10)
async def foo(members: list[rin.Member]) -> None:
    if all([member.created_at < GUILD_MIN for member in members]):
        # remove all members for anti raid
``` Thoughts on this feature (collection) I plan on adding to my DAPI wrapper?
blissful bone
#
@client.command(name = 'event', help = 'shows all active events NOT WORKING')
async def event(ctx):
  for event in ctx.guild.scheduled_events():
    print(event.name)

i having exterme probelms with getting a list of events

** this is the error ive gotten**

nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'list' object is not callable
cloud dawn
pliant gulch
cloud dawn
#

Because i think it looks better, and typing does a better job documenting it.

slate swan
#

How do I write on it?```py
blacklist[str("profile")]["blacklisted"] = "true"

#
                                with open(f"./data/users/{member.id}.json", "r") as f:
                                    user = json.load(f)

                                blacklist[str("profile")]["blacklisted"] = "true"

                                with open(f"./data/users/{member.id}.json", "w") as f:
                                    json.dump(blacklist, f, indent=4)
pliant gulch
#

All the type checkers so far are supporting this as well, no brainer

tacit token
#

hello guys. My problem is this. the fact use dadjoke id
lib: discord_components
code:

@commands.command(aliases=["Facts","facts","Fact"])
    async def fact(self, ctx):
            await ctx.send(embed=discord.Embed(color = 0x990033, title="Did you know? :astonished:", description=f"{random.choice(facts)}"), components=[[
                Button(style=ButtonStyle.green, label="Next", custom_id="button2"),
                Button(style=ButtonStyle.red, label="Stop", custom_id="button3"),
            ]])
        
    @commands.Cog.listener()
    async def on_button_click(self, interaction):
            if interaction.component.custom_id == "button2":
                await interaction.respond(type=7, embed=discord.Embed(color = 0x990033, title="Did you know? :astonished:", description=f"{random.choice(facts)}"))
            
            elif interaction.component.custom_id == "button3":
                await interaction.edit_origin(embed=discord.Embed(color = 0x990033, title="random Facts Stopped!", description=f"If you would like to use it longer, then push the next button or >fact"))

    @commands.command()
    async def dadjoke(self, ctx):
            await ctx.send(embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"), components=[[
                Button(style=ButtonStyle.green, label="Next :arrow_forward:", custom_id="button"),
                Button(style=ButtonStyle.red, label="Stop :octagonal_sign:", custom_id="button1"),
            ]])
        
    @commands.Cog.listener()
    async def on_button_click(self, interaction):
            if interaction.component.custom_id == "button":
                await interaction.respond(type=7, embed=discord.Embed(color = 0x34568B, title="Dad Jokes From CTRL", description=f"{random.choice(dadjokes)}"))
            
            elif interaction.component.custom_id == "button1":
                await interaction.edit_origin(embed=discord.Embed(color = 0x34568B, title="Dad Jokes Stopped! :police_officer:", description=f"If you would like to use it longer, then push the next button or >dadjoke"))
blissful bone
#

woah

cloud dawn
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.

pliant gulch
#

If you didn't know as well I'm rewriting Lefi so now it's a whole different code base

#

πŸ˜”

cloud dawn
slate swan
#

Hm..

cloud dawn
#

Thinking about things to add, i'm currently making a nice wrapper for postgre

tacit token
slate swan
pliant gulch
blissful bone
#

1

slate swan
#

It's over 100.000 chars

#

@-@

blissful bone
#

ur trying to create a blacklist system correct

cloud dawn
slate swan
blissful bone
blissful bone
#

thats where im confused

slate swan
#

set false to true -.-

blissful bone
#

ohhhhh

cloud dawn
slate swan
#

I don't want to use a database

blissful bone
#

user the replace for that

#

use

#

hold on lemme find it

cloud dawn
#

9/10 reasons is because people don't want to learn it. SQL makes your life so much easier.

slate swan
blissful bone
#
 promt_1 = promts["1"].replace("__USER__", f"<@{ctx.message.author.id}>")
slate swan
#

@blissful bone found the problem

blissful bone
#

this is what i used for my ticket bot

slate swan
#

user = json...
blacklist i tried to get -.-

blissful bone
#

lol it happens dont worry

cloud dawn
cloud dawn
blissful bone
#

for replace

shy elm
#

Anyone know how to install the pillow package? I tried the thing from https://pillow.readthedocs.io/en/latest/installation.html but i just get failed to install

unkempt canyonBOT
blissful bone
#
@client.command(name = 'event', help = 'shows all active events NOT WORKING')
async def event(ctx):
  for event in ctx.guild.scheduled_events():
    print(event.name)```

i having exterme probelms with getting a list of events 

 this is the error ive gotten

raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'list' object is not callabl

cloud dawn
#

pip install Pillow

shy elm
silent ermine
#

Hey uhm , how do I give a user a role?

So far i got this: py guild = ctx.guild role = discord.utils.get(guild.roles, name=d2ndQuestion) member = str(applicationID) await member.add_roles(role, reason="Application accepted")

silent ermine
shy elm
shy elm
cloud dawn
shy elm
cloud dawn
slate swan
#

how do i make the bot embed colour be random?

ive done it before but forgot how to.

shy elm
slate swan
#

there was a specific keyword i used which made it unnecessary to get a colour array

unkempt canyonBOT
#

classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/master/api.html#discord.Colour "discord.Colour") with a random hue.

Note

The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.

New in version 1.6.
slate swan
#

ty

arctic eagle
#

Hello,
I am doing a bot with discord.py and I am using a class Name(commands.Cog): ... and i would like to know how i can in this class create a new object from a "subclass" class Type(?) in which I can await to send new messages in the channel.
Example :

class Type(?):
  def __init__(self, channel, smthg):
    ...
  
  ???
  async def print(self):
    await self.channel.send("Test")

class Name(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
    self.obj = Type(channel, ?)
  
  @commands.command()
  async def test_print(self):
    await self.obj.print()
mighty dust
#

how do i make my bot send a DM to the person i mention?

#
async def on_message(self, message):
    for member in message.mentions:
        await member.send('Hi')
#

this is not working

potent spear
potent spear
polar reef
mighty dust
#

but stackoevrflow says there is

#

O_o

potent spear
potent spear
mighty dust
#

ah alr

arctic eagle
potent spear
#

there's not really a need for you to store this as a class... you can perfectly store it as a dict
with the key being the channel_id and the value whatever you like

arctic eagle
potent spear
#

yeah, there's not really a need for a class for each game, you can just store the progress in a db or whatever

arctic eagle
#

for example obj.new, obj.turn, obj.win ...

#

yes but i want to have many instance of the same class fo example if there are 2 games ( match ? ) of the same type

potent spear
#

well, make a subclass for every type of game, there aren't that many, right?

#

your "game" class doesn't need to be subclassed ofc, since it's your superclass

#

that should be an interface / abstract class

storm fable
#

Hey, i want to make an error if a user hasn't enough permissions, but this doesn't work. I use cogs, but i think it should works anyway.

potent spear
slate swan
storm fable
slate swan
dire folio
#

How would I put in a date and time and I would get a timestamp back

slate swan
unkempt canyonBOT
#

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

1641015259.0
slate swan
#

Depending on how you have the date as string you will need to use some other things in the strptime method.

#

And also compare to those I used.

dire folio
#

Ty

median gale
#

yo guys

#

something really cool i added to my bot that u should try out

#

u know how if u have three of ` b4 and after ur message

#

it pulls up this thing

#

ya so i made my bot acc run any code that the user puts and sends any printer output to the channel

#

it makes for a rlly cool python scratchpad

median gale
slate swan
#

oh right, it's snekbox

#

it doesn't run with eval()

median gale
final iron
#

Yeah

final iron
median gale
#

u want code?

final iron
#

No

slate swan
#

make sure that command is owner only my guy

#

otherwise someone is going to exploit it

final iron
#

!e

print("Your idea already exists")
unkempt canyonBOT
#

@final iron :white_check_mark: Your eval job has completed with return code 0.

Your idea already exists
median gale
slate swan
#

yeah, also

median gale
#

WHAT

slate swan
#

!pypi jishaku

unkempt canyonBOT
final iron
#

Your friends can fuck with your system

median gale
#

HOW DARE THEY STEAL MY IDEA

final iron
#

I wouldn't suggest it

final iron
median gale
median gale
final iron
#

You're definitely not

median gale
#

man that sucks

slate swan
#

okay, move on

#

stop cluttering chat

wicked atlas
#

That's not to say you can't try to make your own though

#

It's good learning experience

median gale
#

true

rugged steeple
median gale
#

hmm ya

#

thanks for the advice

rugged steeple
#

!e - A quick example; checking read & write premissions -

import os
from os import W_OK as w
from os import R_OK as r

k = [w, r]
[print(f, i, os.access(f, i)) for i in k for f in os.listdir()]β€Š
unkempt canyonBOT
#

@rugged steeple :white_check_mark: Your eval job has completed with return code 0.

001 | Pipfile.lock 2 False
002 | Pipfile 2 False
003 | config 2 False
004 | snekbox 2 False
005 | user_base 2 False
006 | tests 2 False
007 | LICENSE 2 False
008 | Pipfile.lock 4 True
009 | Pipfile 4 True
010 | config 4 True
011 | snekbox 4 True
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/tuqilufebe.txt?noredirect

vague grove
#

whats the event for on a user dm?

potent spear
#

to check if it's a user dm => message.guild is None

frank tartan
#

USW6GT4

slate swan
#

is making a reaction based or command based ticket system better?

vale wing
#

Button based thinksmart1

#

Jk that's up to you, although users like easier interface which is reactions and buttons

storm fable
median gale
#

thanks

slate swan
#

I have a ticket system and this is the full file https://mystb.in/ChainContinuingTabs.python but then i got this error and when i went and pressed the reaction it didnt make a new channel anymore. Like whenever I deleted the txt file and did everything over again it worked fine but when I reran the bot again, it gave me the same error

#

Can someone help

potent spear
potent spear
# slate swan It does

it does not
2 options
A. you deleted it
B. you key is saved as a string and you pass an int or vice versa

#

why don't you use json for this?

slate swan
#

Cuz I watched a tutorial on it

potent spear
#

yt tutorials suck mostly if we're talking about these libraries

#

they're too concrete or implement bad methods which you can blindly copy paste thinking "if it works, I'm fine with it"

potent spear
#

Like they only talk about what they need, chances are, you need something different which just messes the rest up

#

Greatest example is: they use json as a db

slate swan
#

Oh

potent spear
#

Or even worse in your example: a txt file

slate swan
#

Yeah I realized that

slim ibex
#

json as a db 😬

kindred epoch
manic wing
#

hehehehehehheheehe

#

ill test that command if you want

rare saddle
#

Guys, please tell me why you need it - GUILD MEMBERS INTENT

And - GUILD PRESENCES INTENT

And what is the difference between them?

pliant gulch
rare saddle
rare saddle
pliant gulch
#

No member intent, no member data

#

No presence intent, no presence data

#

Not even any partial data

rare saddle
native wedge
#

how do i make my global error handler send errors in the server?

final iron
craggy cloak
#

You need to update python with pip install discord --upgrade pip discord right?

leaden chasm
#

need help

final iron
#

You're missing a parenthesis

leaden chasm
#

oh

#

ty

#

i'm tired and not concentrating appreciate u

final iron
#

So I've recently learnt that I should keep my database connection open all the time instead of opening and closing it each time

#

I understand that I need a function in my main file connecting to my database

#

I've added that but, now what?

leaden chasm
#

by any chance does anyone know how to get your token hidden (replit)

final iron
final iron
#

I have no idea what I'm doing in this department

native wedge
quaint epoch
#

I don't do that

native wedge
final iron
native wedge
#

why doesnt it send the reason for the error not sending in the channels?

class ErrorHandler(commands.Cog):
    """A cog for global error handling."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
    
    @commands.Cog.listener()
    async def on_command_error(self, ctx: commands.Context, error: commands.CommandError):
        if isinstance(error, commands.CommandNotFound):
            return
        elif isinstance(error, commands.CommandOnCooldown):
            message = f"This command is on cooldown. Please try again after {round(error.retry_after, 1)} seconds."
        elif isinstance(error, commands.MissingPermissions):
            message = "You are missing the required permissions to run this command!"
        elif isinstance(error, commands.UserInputError):
            message = "Something about your input was wrong, please check your input and try again!"
        else:
            message = "Oh no! Something went wrong while running the command!"

        await ctx.send(message, delete_after=5)
        await ctx.message.delete(delay=5)



    def setup(bot: commands.Bot):
      bot.add_cog(ErrorHandler(bot))```
final iron
#

It shouldn't be indented

native wedge
#

like that?

final iron
#

I can't see the indentation but probably

native wedge
final iron
#

Should work

native wedge
#

it only sends here

final iron
#

Is anything sent at all?

#

This should be working unless I'm blind

leaden chasm
final iron
leaden chasm
#

nvm i know the error

#

im using client not bot

#

yeah this error

final iron
#

Did you even read the error?

leaden chasm
#

improper token

#

my token is vaild tho

final iron
#

Print your token and visually compare it to what discord gives you

#

So I figured out how to keep my connection open

#

Would I still have to commit the data I wrote every single time?

limpid thicket
#

Hello, I want my subcommand to be called async def discord(ctx, username = None):
Issue is, I can't reference any objects with discord in it now.
And discord.Embed now doesn't work, any work arounds?

visual island
#

just use the name kwarg at the @command() decorator

#

and change your function name to anything

limpid thicket
#

Oh like you mean like alias?

#

Oh I see, thanks.

#

And name would take priority yes?

visual island
#

yes

magic ore
#

yes

limpid thicket
#

Thanks πŸ‘

pliant gulch
#

woohoo got collectors working 😳

slim ibex
#

What lib is that

pliant gulch
#

This defo doesn't work with events that return more than 1 parameter though, no clue how I'm gonna fix that as of right now

pliant gulch
slim ibex
#

oh you are making your own api wrapper?

pliant gulch
#

I've made one already, I'm making a rewrite of that one rn which is what I just showed

slim ibex
#

oh nice

#

good luck

pliant gulch
#

Thanks

pliant gulch
#

Gonna need to unpack but then it gets harder from there

flat solstice
#

If I want to get the value of a field in a embed I would do something like this right? where the [0] next to fields is the number of the field I am looking forpy message.embeds[0].fields[0].value

quaint epoch
final iron
flat solstice
#

It's complicated and I'm too tired to explain it but basically I'm making a task event which checks channel A for any msgs containing specific words (Warn, Ban, Mute, Kick) and if it finds a msg with that in the msg embed title then it constructs a embed with the values of the first embed and sends this second embed to channel B.

@final iron @slim ibex @quaint epoch

And this is what I have so farpy @tasks.loop(minutes = 60) async def moderation_logs(self): key_words = ["WARN", "MUTE", "UNMUTE", "KICK", "BAN", "UNBAN"] checked_logs = [] # A list of ID's of the messages the bot has checked, Probbabrbly should be written to my DB case_count = 0 # A incrementing number for the moderation case's, will be written to my DB moderation = self.bot.get_channel(id = 885569667861717042) # The channel it is sending the new msg to clifford_log = self.bot.get_channel(id = 500768218257031168) # The channel it is searching with moderation.channel.typing(): messages = await clifford_log.channel.history(limit = 10000)#.flatten() for message in messages[0:]: # Making the bot search through the messages chronologically (I think) if message.id not in checked_logs: if message.author.id == 776782769312628746: # Checking the message author is my other bot which is causing me to make this lenghty workaround if len(message.embeds) > 0: if key_words in message.embeds[0].title: # Checking in my keywords are in the retrived embed title, I want it to make a count of how many times it finds each word and I'm thinking a dict would be good but I'm not too sure how to go about that rn embed = discord.Embed(title = f"Case {case_number} | {action}", colour = self.bot.config.error_colour, timestamp = message.timestamp) embed.set_author(name = f"{message.embeds[0].fields[0].value} | {message.embeds[0].fields[0].value.id}", icon_url = message.embeds[0].fields[0].value.avatar_url) embed.set_footer(text = f"{message.embeds[0].fields[1].value} | {message.embeds[0].fields[1].value.id}", icon_url = {message.embeds[0].fields[1].value.avatar_url}) embed.add_field(name = "Offender", value = message.embeds[0].fields[0].value, inline = True) embed.add_field(name = "Moderator", value = message.embeds[0].fields[1].value, inline = True) if message.embeds[0].fields[3]: # The 4th field of the original embed doesn't always appear so i'm accounting for that embed.add_field(name = "Duration", value = message.embeds[0].fields[3].value) embed.add_field(name = "Reason", value = message.embeds[0].fields[2].value) checked_logs.append(message.id) # Writting the ID of the latest checked msg to a list so it knows not to check this again await moderation.send(embed = embed)

quaint epoch
#

Maybe read the docs or convert the embed to a dict to test it, Idk

#

I'm not sure how to work with that

flat solstice
#

i'm like 60% sure it'll work, I just need to make sure I have all the logic sound and that I am pulling all of the values correctly, even if their not in the correct places i'll still count it as a win

pliant gulch
potent spear
#

you mean "other python libraries?"

#

nice letter

#

username checks out

jade jolt
#

heh its true

glad thicket
#

My question is this when you get all of the items in a collection in mongodb using pymongo What kind of list will you get

import pymongo
client = pymongo.MongoClient('URL')
db = client.db
collection = db.collection
document = list(collection.find({})

The database is like this

{
  "_id": {
    "$oid": "ID"
  },
  "question": "question",
  "answer": "answer"
}

Can anyone tell me how the list is going to be like

#

this is for a discord bot

#

NeverMind I already Got the answer

#
[{'_id': ObjectId('ID'), 'question': 'question', 'answer': 'answer'}]
green bluff
#

breh

#

im literally so bad at coding

wicked atlas
#

also, ctx.send() should be awaited

green bluff
#

oh yes i forgot also my bot has admin

#

perms

wicked atlas
#

can you send the full error traceback?

green bluff
#

ye nah i figuired it out its just that the bots role was below the muted role

#

im just bad at coding lol

slate swan
abstract aspen
glad thicket
#

Hey can anyone answer my simple question

#

I created an embed command that will make an embed like &embed Hello "This is it" FFFFFF

#

But when I tried to put in a nitro animated sticker it justs shows the text of the emoji

boreal osprey
#

im trying to make a help command where i can use a input

File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'message' is not defined
vocal plover
glad thicket
slate swan
#

titles can now show custom emojis iirc

glad thicket
#

like :arrow:

vocal plover
#

Does the bot share a server with the emoji?

glad thicket
#

yes

boreal osprey
#
@bot.command()
async def help(ctx):
    emb=discord.Embed(title = "Help commands", color = discord.Colour.random())
    emb.add_field(name = "List of command types", value = "fun, moderation", inline = False)
    await ctx.send(embed=emb)


    if "fun" in message.content:
        e=discord.Embed(title = "fun commands", description = "insert commands", color = discord.Colour.random())
        await message.send(embed=e)

can someone show me what im supposed to do

glad thicket
glad thicket
vocal plover
#

Those are the only reasons it would break, unless your command modifies the text in some way, since embed descriptions should handle emojis from mutual servers fine

slate swan
# glad thicket like :arrow:

Use the escaped name of the emoji and make sure that the bot is in the server the emoji is from , escaped name can be get from using \:emoji\:

heavy folio
#

also subclass HelpCommand, not remove it

#

!d discord.ext.commands.HelpCommand

unkempt canyonBOT
#

class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).

This means that relying on the state of this class to be the same between command invocations would not work as expected.
covert otter
#

I recently reorganised my code for my discord bot, and the cogs aren't in a child directory anymore but in a parent directory. I have tried things like:

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

What am I doing wrong?
heavy folio
#

show your dir

slate swan
#

you need to load them as cogs.CogFolder.{filename[::-3]}

#

Since you are looping inside that path

sonic gale
#

hello, how would i get my discord bot to read a status and give a role. for example, i put /myserver in my status and the bot will apply roles to the user

potent spear
slate swan
#

!d discord.Member.activity

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
sonic gale
#

oh

#

that helped. i just need a general idea

slate swan
#

use this in on_member_update , check the activity.name , it will return an str form of the user's status

#

emoji_88 My wifi oof

covert otter
glad thicket
glad thicket
#

inside the code

covert otter
slate swan
covert otter
slate swan
#

@quaint epoch You can have member.guild_permissions , or channel.permissions_for(member)

slate swan
quaint epoch
#

thanks lol

slate swan
#

yw

covert otter
# slate swan show your imports

from asyncio import events from distutils.log import error from http import client from multiprocessing.connection import Client from operator import truediv from pydoc import describe from sre_constants import CATEGORY_LINEBREAK from telnetlib import OUTMRK from textwrap import indent import discord from discord.ext import commands import os from tokens import TOKEN import json

topaz steppe
#

@novel apex

slate swan
#

!e import os
os.os

unkempt canyonBOT
#

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

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

This is what u did somewhere

covert otter
surreal sierra
#

hey, could someone help me with these errors? I got the same code from an older bot and it works fine there. I have the code for the bot shared up in different files also

  File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Admin\PycharmProjects\The-KnightBot\commands.py", line 12, in <module>
    async def setup1(ctx):
  File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\core.py", line 1433, in decorator
    return cls(func, name=name, **attrs)
  File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\core.py", line 242, in __init__
    raise TypeError("Aliases of a command must be a list or a tuple of strings.")
TypeError: Aliases of a command must be a list or a tuple of strings.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Program Files\Python310\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Admin/PycharmProjects/The-KnightBot/main.py", line 21, in <module>
    import discord_events
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\Admin\PycharmProjects\The-KnightBot\discord_events.py", line 2, in <module>
    from main import *
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.2.3\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "C:\Users\Admin\PycharmProjects\The-KnightBot\main.py", line 41, in <module>
    bot.load_extension("commands")  # use name of python file here
  File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Admin\PycharmProjects\pythonProject1\venv\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'commands' raised an error: TypeError: Aliases of a command must be a list or a tuple of strings.
native wedge
#

Using cogs i can seperate commands into groups right?

sweet pilot
#

yeah

slate swan
slate swan
surreal sierra
#

its working now tho, ty

covert otter
slate swan
covert otter
slate swan
#

That's weird ,. Cause that is what the error says , show the imports in the cog

pine crown
#

how to make it so that once somebody uses a slash command for a bot, the next message they send will be set to a variable

#

how to make it so that once somebody uses a slash command for a bot, the next message they send will be set to a variable

#

how to make it so that once somebody uses a slash command for a bot, the next message they send will be set to a variable

potent spear
pine crown
#

i want to make a mod log

#

thing

potent spear
#

just create a botvariable which stores the data based on the user id

pine crown
#

so when they kick or unban or ban it will be sent there

potent spear
#

that's just an argument...

covert otter
potent spear
potent spear
covert otter
pine crown
#

how to make a commands logging system>

#

so

#

they sent a command like /kick

#

then once the user is kicked it will send the output in a channel that the server owner set the channel id to

final iron
#

With the channel id

#

Then just get the id, fetch the channel and send the message

#

With a little trickery you can make a cog specific check so whenever a command in the cog is used it will log it

pine crown
final iron
pine crown
#

every server the bot is in

#

and they will set the channel id

final iron
#

Yeah, you would need a database

#

I don't know anything about the pros and cons of the different db's but I use sqlite3 and its dead simple

pine crown
final iron
#

With what?

pine crown
#

with making the mod log

#

im struggling

dawn elbow
#

hey guys

#

i like python

pine crown
#

cool

final iron
#

I can help with ideas on how to do it and errors you encounter but I'm not going to spoonfeed you code

pine crown
#

yes

final iron
pine crown
#

in making it

#

how do i use the sqlite

final iron
#

A really nice interactive website to help you learn

#

Its dead simple and you'll most likely pick it up in 1-5 days

#

But no guarantees

pine crown
#

do you know how to use mongodb?

final iron
#

Nope

pine crown
#

wait i found that there is module for sqlite

slim ibex
#

yes

final iron
#

You wouldn't want to use the built in lib

#

Its blocking

slim ibex
#

aiosqlite

final iron
#

!pypi aiosqlite

unkempt canyonBOT
final iron
#

You would want to use this

cloud dawn
#

!pypi asyncpg

unkempt canyonBOT
cloud dawn
#

:3

slim ibex
#

asyncpg is for Postgres

pine crown
#

hjmm

slate swan
#

!paste it would be long so consider using this

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.

maiden fable
slate swan
#

Hey

#

Is it possible to use a file as argument

boreal ravine
pliant gulch
#

Just take in a str as the file's name

#

then open a file pointer with the name

slate swan
#

Lika ataching the file and uploading it to specific directory

pliant gulch
#

E.g Message.attachments

#

!d discord.Message.attachments

unkempt canyonBOT
boreal osprey
#

apparently this body form is invalid and idk why

Traceback (most recent call last):
  File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\***\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.5.value: This field is required
#
@bot.command(aliases = ['whois', 'ui'])
async def userinfo(ctx, member : discord.Member = None):
    
    if member == None:
        member = ctx.author

    roles = [role for role in member.roles][1:]

    emb=discord.Embed(title = f'{member.name} user info', color = discord.Colour.random(), timestamp = ctx.message.created_at)
    emb.set_thumbnail(url=member.avatar_url)
    emb.set_footer(text=f'Requested by {ctx.author.name}')
    emb.add_field(name="nickname", value=member.display_name, inline=False)
    emb.add_field(name="Discord name", value=member.name, inline=False)
    emb.add_field(name="ID", value=member.id, inline=False)
    emb.add_field(name="account creation date", value=member.created_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline = False)
    emb.add_field(name="server join date", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline = False)
    emb.add_field(name = f'roles ({len(roles)})', value= " ".join([role.mention for role in roles]), inline = False)
    emb.add_field(name="top role", value=member.top_role.mention, inline = False)
    emb.add_field(name='Is bot?', value=member.bot, inline=False)
    await ctx.send(embed=emb)
potent spear
#

emb.add_field(name = f'roles ({len(roles)})', value= " ".join([role.mention for role in roles]), inline = False) are you sure roles contains something?

#

also, I'm not sure on the last line if value can be a boolean

boreal osprey
potent spear
cloud dawn
#

field 5 == ```
emb.add_field(name="server join date", value=member.joined_at.strftime("%a, %#d %B %Y, %I:%M %p UTC"), inline = False)

#

Joined at states

#

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

#

None == empty

potent spear
#

aight, I just miscounted the field woops

boreal osprey
#

i think im to stupid to understand what im supposed to do

potent spear
#

anyways, you should add checks before adding certain fields I guess

boreal osprey
#

ah