#discord-bots

1 messages · Page 746 of 1

vale wing
#

Then I suggest you to complete that guide first, discord bot is an advanced asynchronous application which requires decent knowledge

kind wind
#

Yeah I dont have much time with schools and everything but i try to find time to read it

vale wing
#

You should read it, you will understand python much better 👍

#

And once you get enough experience and knowledge you will build your discord bot on python :)

#

Good luck

kind wind
#

Ill try now where will i put the variable? on line below the as file: , before or inside that line

vale wing
#

You know about files reading?

kind wind
#

no

#

so you want me to do it by myself?

vale wing
#

I mean I can explain that lol

kind wind
#

i have to go... ill be here tmr and ask again

vital niche
#

Hello good day, I just finished learning the basic of python and I want to create my first goal which is discord bot. Is there any tips you can give me?

cloud dawn
#

Any way to format Discord's datetime into embeds?

#

The <t:1642020999:R>

vale wing
cloud dawn
#

Like
Posted: <t:1642020999:R>

vale wing
#

As far as I know footer doesn't support discord markup

cloud dawn
#

Tried it in other fields aswell it just nopes

#

Why can't we have nice things ;-;

vale wing
#

In other fields it should be fine?

#

If it is a value a field and not a title

cloud dawn
vale wing
#

Titles don't support markup as well

final iron
cloud dawn
#

Wait idea

final iron
#

Atleast the timestamp auto updates

vale wing
#

You could make your own function that would return the string you need

#

But it won't autoupdate tho

cloud dawn
vale wing
#

It returns the timestamp markdown

#

I mean return something like just 5 minutes ago (but as said it won't autoupdate sadly)

cloud dawn
#

yeah but i think it's kinda pointless to put in the date since it is already on top.

final iron
#

If you do ctx.message.created_at in the timestamp it will auto update

cloud dawn
final iron
#

Ah

vale wing
#

Interaction has something like that as well afaik

cloud dawn
vale wing
#

Nvm it's something different

cloud dawn
#

feature request yeet

vale wing
#

<t:0>

#

😳

cloud dawn
#

<t:12222222222222222:R>

#

Lol

vale wing
#

On pc it's invalid date and here on phone it is 20 Sep 5838270

weary mirage
#

I'm getting this error :
Command raised an exception: InterfaceError: Error binding parameter 1 - probably unsupported type.
after running this :
cur.execute("INSERT INTO orders(customer, customerid) VALUES (?, ?)", (str(user), (str(cust),)))

cloud dawn
vale wing
#

\u thing yes

cloud dawn
#

I can't remember the \u thingy

#

This is easier to remember

weary mirage
#

sqlite3

vale wing
#

Well I don't typically use params thingie, not sure how it works

jade tartan
#

Can someone please help me make a discord dashboard please?

#

i need help

weary mirage
#

when I run this (missing the other value being inserted) :

cur.execute("INSERT INTO orders(customer) VALUES (?, ?)", (str(user)))

it works, but not when I try inserting another value in there :(

onyx elbow
#

i currently made a very simple discord bot for the first time but i want to add more to it does anyone have any good ideas i could add to it

vale wing
#

What's the type of customerid? @weary mirage

weary mirage
#

erh how can I tell?

#

cur.execute('''CREATE TABLE IF NOT EXISTS orders (customer, customerid, deliverystat, orderstat)''')

vale wing
#

Didn't you create this database?

cloud dawn
weary mirage
#

this is all I put when creating the table

vale wing
#

You usually specify column type

weary mirage
#

oh

#

is that what might be the issue?

vale wing
#

Probably

cloud dawn
jade tartan
# vale wing Site?

Well no error but ```
from quart import Quart, request
from discord.ext.dashboard import Server

app = Quart(name)
app_dashboard = Server(
app,
"secret_key",
webhook_url="",
sleep_time=1
)

@app.route("/")
async def index():
guild_count = await app_dashboard.request("guild_count")
member_count = await app_dashboard.request("member_count", guild_id=776230580941619251)

return 

@app.route("/dashboard", methods=["POST"])
async def dashboard():

await app_dashboard.process_request(request)

if name == "main":
app.run(debug=True)

Am trying to make this direct me to the discord login page
How do i do that?
cloud dawn
weary mirage
#

okay I think I might know the problem

cloud dawn
jade tartan
#

the discord-ext-dashboard?

cloud dawn
vale wing
#

That exists? Wow

cloud dawn
jade tartan
#

ohh ok which is quart-ext-dashboard?

cloud dawn
#

!pypi Quart-Discord

unkempt canyonBOT
vale wing
#

O

jade tartan
#

that prob will make my life easier

weary mirage
#

I figured out the issue, I was setting the value as a string, and I guess that wasn't good 🤷‍♂️

cloud dawn
#

This is only for oauth though but it's nice since you don't need to bother with that again.

cloud dawn
unkempt canyonBOT
cloud dawn
#

Combine with this and you got a baby

#

The website AND Discord bot have to both be hosted on the same host. Else you have to make your own API.

jade tartan
#

Wdym the same host?

cloud dawn
jade tartan
#

ohh ok well theres only showing me pip install nothing else on those 2 ext that you just mentioned?

jade tartan
#

yeah

#

so i dont know how am i gonna make it

#

could just look at yt vids

cloud dawn
#

I do have an example i think somewhere in my back pocket..

vale wing
#

Interesting extensions

cloud dawn
#

Friend of mine made a good easy example.

#

Though ALL the code is not getting updated so with this you can get the hang of it but i do recommend making your own IPC or API.

jade tartan
#

ok how do i make my own API?

grand shell
#

hey guys, does anyone know how I can retrieve all messages in a channel that were sent in the last hour? iv been trying to do it for ages but I cant get it working.

jade tartan
#

i dont want cogs

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
cloud dawn
vale wing
#

Use after param

cloud dawn
grand shell
jade tartan
#

Was before

cloud dawn
# grand shell omg ty

Do make a check though if in this channel for example you go trough all messages of the last hour it's going to take awhile.

cloud dawn
vale wing
#

Cogs are good 1010

cloud dawn
#

Well guys

#

We need a Discord topics command

#

.topic

lament depotBOT
#
**What's one feature you wish more developers had in their bots?**

Suggest more topics here!

cloud dawn
#

cogs

final iron
#

imo thats a very bad topic

#

.topic

lament depotBOT
#
**Do you think there's a way in which Discord could handle bots better?**

Suggest more topics here!

final iron
dire folio
#

how would i make a command that removes a role from everyone who has it

final iron
#

!d discord.Role.members

unkempt canyonBOT
final iron
#

@dire folio

jade tartan
#
'git' is not recognized as an internal or external command,
operable program or batch file.``` i wanna add a depoisitory but it wont work
#

How do i add it

#

@cloud dawn

slate swan
#

Guys pls help I can't find an uptime command without cogs

final iron
slate swan
#

I can't learn how to use them

final iron
#

Why?

cloud dawn
slate swan
# final iron Why?

They're difficult and English is not my main language so I don't understand them completely

cloud dawn
slate swan
#

Don't know variables too. I'm new : D

elder pike
cloud dawn
slate swan
#

Well I edited the cog settings to remove them and the uptime cmd works fine...

#

I have this code, and in theory, as soon as a member joined the server, it would give a role. But that's not happening. Can anyone help?

@client.event
async def on_member_join(member):
    role = discord.utils.get(member.server.roles, name = "teste")
    await client.add.roles(member, role)```
final iron
#

!d discord.Member.add_roles

unkempt canyonBOT
#

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

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

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

This is what you're looking for

slate swan
#

still not working

#

oh

#

wait

#

like this, right?

final iron
#

No

slate swan
#

oh

final iron
#

You use use member which is your discord.Member object

#

And I would suggest you actually read the docs I sent

pliant gulch
# elder pike

You'd use self instead of MyClient for get_channel as self is the instance not the class

elder pike
shut leaf
#

Hello

#

can sm1 help

final iron
shut leaf
cloud dawn
slate swan
#

Anyone?

cloud dawn
slate swan
#
import datetime
from discord.ext import commands, tasks

class Dates(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_ready(self):
        current_time.start()
        
    @tasks.loop(hours=1) 
    async def current_time(self):

        now = datetime.datetime.now()
        now = now.strftime("%d/%m/%Y às %H:%M:%S")

        channel = self.bot.get.channel(914569334985216060)
        await channel.send("Data atual: " + now)

def setup(bot):
    bot.add_cog(Dates(bot)) ```
shut leaf
cloud dawn
unkempt canyonBOT
#

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

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

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

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

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

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

solved one part but gave problems in another

#

channel = self.bot.get.channel(914569334985216060)
AttributeError: 'Bot' object has no attribute 'get'

cloud dawn
#

get_channel

slate swan
#

oh

#

my bad

#

ty <3

jade tartan
tranquil badge
#

Trying to make a testmode command so that my bot will only respond to me. Already have some commands that only I can use with is_owner() but I can't find a way to lock all commands to be able to only be ran by me when I run testmode

left crater
#
async def on_member_ban(self, member: discord.Member):
        channel = self.bot.get_channel(814956709290049596)

        if not channel:
            return
        await channel.send(f"{member} was banned
!")```
#

when someone gets banned i want the bot to say user was banned

pliant gulch
#

Just override on_message and only process_commands if the message's author id is the same as yours

left crater
slate swan
#

Can someone explain to me why the bot stays on, puts a custom status but does not respond to commands?

import discord
import random
from decouple import config
from discord.ext import commands

client = discord.ext.commands.Bot(command_prefix = "?", help_command = None)

# <-- Eventos -->

@client.event
async def on_ready():
    activity = discord.Game(name = 'PokéCenter no topo! Prefix: ?help', type=3)
    await client.change_presence(status=discord.Status.online, activity=activity) 
    print('Pronto para uso {0.user}' .format(client))

@client.event
async def on_message(message):
    if client.user.mentioned_in(message):
        await message.channel.send("**:pika_style: ・ Ei, meu prefixo é ``?``, use ``?help`` para mais informações!**")

# <-- Comandos -->

@client.command(name = "ola")
async def ola(ctx):
    await ctx.send(f'Teste {ctx.author}')

@client.command(name = "dado")
async def dado(ctx, numero):
    variavel = random.randint(1,int(numero))
    await ctx.send(f':game_die: | {ctx.author.mention} E o número que você rolou é **{variavel}**!')

@client.command(name = "help")
async def help(ctx):
    embed = discord.Embed(title=":mailbox: ・ Veja abaixo minha lista de comandos!", colour=discord.Colour.green())
    embed.add_field(name="``?help``", value=" :setagreen: Mostra todos os comandos e suas funções do bot", inline=False)
    embed.add_field(name="``?dado (número)``", value=" :setagreen: Escolhe um número aleatório de acordo com o número escolhido", inline=False)
    embed.add_field(name="``?startl``", value=" :setagreen: Mostra a tierlist dos melhores iniciais para pvp! (Atualizado)", inline=False)
    embed.add_field(name="``?gymtl``", value=" :setagreen: Mostra a tierlist dos melhores ginásios da PokéCenter! (Atualizado)", inline=False)
    embed.set_footer(text=f"PokéCenter | Mensagem requerida por {ctx.author.name}")
    embed.set_thumbnail(url=ctx.author.avatar_url)

    embed2 = discord.Embed(title=":correto: ・ A minha lista de comandos foi enviada em seu privado!", colour=discord.Colour.green())
    await ctx.send(embed=embed2)
    await ctx.author.send(embed=embed)

    await ctx.message.add_reaction(":correto:")

@client.command(name = "startl")
async def startl(ctx):
    await ctx.channel.send(file=discord.File('imgs/iniciais1.png'))

@client.command(name = "gymtl")
async def gymtl(ctx):
    await ctx.channel.send(file=discord.File('imgs/lideresgym.png'))

# <-- Configs -->

TOKEN = config("TOKEN")
client.run(TOKEN)```
#

(The code is not mine, it's from a person I'm trying to help who doesn't speak English and I got confused too)

tranquil badge
# cloud dawn You could make cog checks.

So i read the docs on what checks were. It seems like that would work but I'd need the bot to be in a perpetual state of checking if the author is me when I put it into testmode.

slate swan
#

@cold sonnet

#

anybody have a code example of a command using buttons with dpy 2.0? just switched up to 2.0 and the third party components dont work anymore.

slate swan
#

panda

unkempt canyonBOT
cloud dawn
slate swan
#

can you help me?

cloud dawn
#

Does the bot work if you don't do a custom status?

tranquil badge
slate swan
#

I took that part of the code out and it still doesn't work

#

It's not that it doesn't work. It works. It's just not responding to commands

tranquil badge
#

Just gotta figure out how to implement

slate swan
#

For example, when I ping him, he answers me. But when I try to run a command, it doesn't respond.

cloud dawn
#

@slate swanhttps://discordapp.com/channels/267624335836053506/343944376055103488/794484840078376976

tranquil badge
#

@cloud dawn is there an example for process_commands? I can't think of how to implement it

tranquil badge
#

Thanks

tawdry flume
#

.

#

Sus

#

.

final iron
tawdry flume
#

I know

frank tartan
#

SO WHY

jade tartan
#

I need help install bot template via git

#

Does any one know?

cloud dawn
#

just clone it

jade tartan
#

Wdym

slate swan
#

How do I create a leaderboard command? I have seen videos on that topic on YouTube, but I don't really get it. If you don't mind, kindly explain the code to me, and I use json to store everyone's data.

slate swan
cloud dawn
unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

sql is so easy to learn thats the thing smh

slate swan
# cloud dawn !blocking

But I used json to make an economy system, and it worked. (PS: I'm new to coding with Python)

frank tartan
#

so i have a command where the user can setup the bot, but they need to input roles. How can I check to verify that those roles exist?

#

PLEASE PING IN REPLIES AND IF YOUR TALKING TO ME IN GENERAL

slate swan
#

!dictionary

cloud dawn
frank tartan
slate swan
#

Can someone help?

pliant gulch
#

self.restart_bot as it's a method of your class. Also you aren't actually closing the bot itself before resetting so that would mean you get two processes

cloud dawn
#

Just regular typehint ```py
@bot.commad()
async def test(ctx: command.Context, role: discord.Role) -> Optional[Message]:

frank tartan
frank tartan
slate swan
#

and thanks btw

jade tartan
slate swan
#

I always forget the self

jade tartan
#

it doesnt seem to work

cloud dawn
unkempt canyonBOT
#

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

This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.

Changed in version 1.1: The `cls` parameter can now be passed.
jade tartan
#

@cloud dawn

pliant gulch
slim ibex
cloud dawn
cloud dawn
#

If you are using cogs.

jade tartan
#

its making me sign in

#

but neither of them work

slate swan
frank tartan
slate swan
#

thanks for the advices @slim ibex and @pliant gulch

jade tartan
#

nope aint really working for me

#

nvm ill just maybe do it with node.js

hoary cargo
#

sadgebye pov you can't install a library

cloud dawn
#

lmao

frank tartan
slate swan
frank tartan
#

@slate swan i dont wanna be nosy, but are you done?

crisp bloom
#

can someone help me

#

it is giving me an error on this line

torn sail
slate swan
torn sail
slate swan
slate swan
tough lance
#

Hi

slate swan
torn sail
#

wdym

slate swan
#

Instead of if discord.utils.get(ctx.guild.roles, name="x") in ctx.guild.roles, I made it a variable to lessen what I write

#
@bot.command()
async def check(ctx,roles: discord.Role):
    role = discord.utils.get(ctx.guild.roles, name=roles)
    if role in ctx.guild.roles:
        await ctx.send("The role is on the                           server. ")
     else:
         await ctx.send("The role is not on the server.") 

@frank tartan

torn sail
#

no

slate swan
#

Wait lemme make it better

torn sail
#

dont use discord.utils.get

slate swan
#

Why

torn sail
#

role converts it to discord.Role and if its not in the server it raises an error

torn sail
#

im just saying thats a lot more code than you need

pliant gulch
#

The utils.get here is completely un-needed

torn sail
#

yeah

pliant gulch
#

typehinting roles to discord.Role already internally runs a role converter

#

So roles would be a discord.Role object already

slate swan
#
@bot.command()
async def check(ctx,roles: discord.Role):
    role = roles
    If role in ctx.guild.roles:
        await ctx.send("The role is on the server. ")
    else:
         await ctx.send("The role is not on the server.")
#

Wait

pliant gulch
#

roles has to be in the server otherwise it will raise an error

#

Since it's using the role converter

torn sail
#

andy is correct

pliant gulch
#

Just make a command specific error

#

And check if it raises the NotFound or whatever error it was

#

!d discord.ext.commands.RoleNotFound

unkempt canyonBOT
#

exception discord.ext.commands.RoleNotFound(argument)```
Exception raised when the bot can not find the role.

This inherits from [`BadArgument`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BadArgument "discord.ext.commands.BadArgument")

New in version 1.5.
slate swan
#

I just want to learn how to make a chatbot

#

Or an interactive bot

#

I tried making a 2 player game with global variables, but once other people used it simultaneously, the bot broke.

#

Should I use a file to store the players' names or ids? @pliant gulch

frank tartan
#

so

slate swan
#

Does it work?

frank tartan
slate swan
pliant gulch
frank tartan
#

yes but i ran into an error while saving it to a json file

#

TypeError: Object of type Role is not JSON serializable i get this error and i have no idea what it means

pliant gulch
frank tartan
pliant gulch
slate swan
frank tartan
#

i have a command that saves it to a json file, but when i run it i get the command

pliant gulch
#

Just not logical nor is it how it should work

frank tartan
pliant gulch
#

You could store the ID, the name, etc

#

Not the object itself

slate swan
#

How will I do it tho?

#

Coding on phone is a pain in the ass

frank tartan
pliant gulch
#

Access the property on the role object

hoary cargo
slate swan
frank tartan
#

ok i figured it out @pliant gulch ty

slate swan
#

I have got no other choice

slate swan
slate swan
hoary cargo
#

Just wait until class is done, that's it

slate swan
#

class is important topithink

#

I'm done with my sch work

#

But I still have to be in class

hoary cargo
#

@slate swan why u here again sadgebye

frank tartan
slate swan
#

I'll just suffer not coding

slate swan
hoary cargo
#

hmmsip you can not

slate swan
hoary cargo
#

Federal reasons

slate swan
#

Who knows how to create a leaderboard command?

crisp bloom
#

So... I am using this for users to ban people on the server using their id, but idk how to implement a try and exept block so if the user enters a wrong id it says "user not found"

#

is there a correct way to do this?

patent lark
#

thats very wrong.

crisp bloom
#

lmao I know

patent lark
#

on_command_error is an event, not something you can just accept

crisp bloom
#

yeah I for some reason thought that would work

patent lark
#

and use a member object, rather than converting the id parameter to a discord.User Object, and plus, you call the API for every user which is unnecessary

crisp bloom
#

wdym member object

patent lark
#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
patent lark
#

bot.fetch_user() returns the discord.User object, which doesnt have a ban method.

#

ah you're unbanning

crisp bloom
#

yea

patent lark
#

i recommend you read the documentations before continuing.

frank tartan
#

when I run

@client.command()
@commands.has_permissions(administrator=True)
async def currentSettings(ctx):
    with open("channels.json", "r") as fp:
        chanData = json.load(fp)

    with open("players.json", "r") as pl:
        plaDada = json.load(pl)

    with open("teams.json", "r") as ts:
        teaDada= json.load(ts)

i get this error.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Extra data: line 1 column 21 (char 20)

{"Offer": "Not set"}{"transactions": "Not set"}{"demands": "Not set"}

that is in channels.json, the others just have []. I know the problem, but have no idea how to prevent it. Because I put stuff into the json files using this command

@client.command()
async def saveSettings(ctx):
    with open("channels.json", "w") as file:
        json.dump({"Offer": offerChannel}, file),
        json.dump({"transactions": transactionChannel}, file),
        json.dump({"demands": demandChannel}, file)

    with open("teams.json", "w") as file:
        json.dump(teamList, file)

    await ctx.reply("I have saved all settings.")
patent lark
#

your solution would be to use a database to store data, not json.

frank tartan
rotund creek
#

Anyone know how I can get user object with pycord?

#

From given id

wicked atlas
frank tartan
tough lance
#

aiosqlite (SQL)
ayncpg (PostgreSQL)
motor (MongoDB)

wicked atlas
frank tartan
wicked atlas
#

not sure why it's appending it tho, thats a bit weird

tough lance
#

Put a {} in the file also

frank tartan
frank tartan
wicked atlas
#

well first of all, use a database, but you can just dump one dict like this

my_dict = {"key":"value", "2ndkey":"2ndvalue"}
json.dump(my_dict, file)
frank tartan
wicked atlas
#

Can you send the full error? It looks like you're opening a few json files, so it might not be on the line you think it si

frank tartan
# wicked atlas Can you send the full error? It looks like you're opening a few json files, so i...
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 167, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\user\OneDrive\Desktop\league bot template\main.py", line 86, in currentSettings
    plaDada = json.load(pl)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The above exception was the direct cause of the following exception:
#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 351, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\user\OneDrive\Desktop\league bot template\main.py", line 32, in on_command_error
    raise error
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 994, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 894, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 176, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
wicked atlas
#

check whatever json you're loading there

slate swan
#

The json does not have a {} probably

frank tartan
#

but how do you suggest i fix that?

slate swan
#

Do it manually

frank tartan
#

but I want to save settings using commands... not manually

slate swan
#

json is not a database , so u need to do that thing manually

#

No other way around

frank tartan
brave tulip
#

anyone know what i can use to change the text under the bot profile

#

like Listening to spotify for an example

#

just my own thing

wicked atlas
frank tartan
#
activity = discord.Game(name="STATUS YOU WANT HERE", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
#

that should work, its what i use

brave tulip
#

to change the bots text

slate swan
wicked atlas
frank tartan
wicked atlas
wicked atlas
brave tulip
#

wym what library

slate swan
#

Didn't work is not a thing , "I was unable to learn it" is

frank tartan
brave tulip
#

theres more functions that do the same thing?

frank tartan
#
activity = discord.Game(name="STATUS YOU WANT HERE", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
wicked atlas
#

woop

brave tulip
slate swan
#

no worry

brave tulip
#

that should work though

wicked atlas
frank tartan
#

it works on my bot

wicked atlas
brave tulip
#

thats a lot of args

#

or i am maybe reading it wrong

slate swan
#

You don't need use everything given in the docs ,

#

Just use the params u need

#

Like activity and status

brave tulip
#

also i wonder how does sql fetch data in python

#

like is it always an array of stuff

#

i'm just grabbing a number and using cursor.fetchall()

drifting arrow
#

is it possible to use an array in @commands.has_any_role("admin")?

#

say @commands.has_any_role(my_roles_list['roles'])?

magic ore
#

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

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

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

has_any_role('role', 123, ...)

#

you can unpack the list

wicked atlas
#
@commands.has_any_role(*my_roles_list)
drifting arrow
wicked atlas
#

What does your list look like?

drifting arrow
wicked atlas
#

Is that a part of a dict?

#

Then you want to get that key's value, then unpack that

#
*that_dict["roles_baninfo"]
drifting arrow
#

Yes I'll be targeting that specific part

#

My variable will look like this:

myvariable = mydictionary['roles_baninfo']
slate swan
wicked atlas
slate swan
#

is it possible to get the id of a role using its name?

slate swan
wicked atlas
slate swan
#

nice ty

drifting arrow
#

What's the documentation to look up for limiting a command to a specific channel

wicked atlas
drifting arrow
#

😦

wicked atlas
slate swan
#

how would i assign a role to a user by using their id

drifting arrow
#

are you passing the user mention into the command?

#

Or is the bot doing it on join?

#

The targeting method changes based on how the command triggers

tranquil badge
#

I sent a message earlier about trying to make a test mode command that only i can use and prevents anyone from being able to use regular commands.

@bot.event
async def on_message(message):
    owner_id=352986404621647873
    if message.author.id == owner_id and message.content == '!testmode':
        channel = message.channel
        await channel.send('**`Now in test mode.`**')
        await bot.process_commands(message)

With it set up like this it prevents all commands.

Could I do a normal command like

@commands.command(name='testmode')
@commands.check(on_message):
#

I'm probably miss understanding something about this

drifting arrow
slate swan
unkempt canyonBOT
#

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

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

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

get the user or use a arg and use the coro

pliant gulch
drifting arrow
#

You can get the user using one of the methods I mentioned above.

pliant gulch
slate swan
unkempt canyonBOT
slate swan
slate swan
drifting arrow
slate swan
#

i want to make a bot command that will respond to a direct message, how do i do this?

drifting arrow
slate swan
drifting arrow
# slate swan he said get the user by id

Yes. it's a case of how does he want to grab it? is he parsing it through the variable specifically? or is he just doing an @ ?
or is it on member join? or does the bot grab every member in the discord and assigns roles?

drifting arrow
#

I've always thought it was a pre-define

slate swan
drifting arrow
#

Anyway. it's still about how he's grabbing the member. at which step does he need to worry about?

slate swan
unkempt canyonBOT
#

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

1
slate swan
#

I dont mean to spam but: i want to make a bot command that will respond to a direct message, how do i do this?

#

Like the first time I dm the bot, it will send one message. The second time, it will send another. Then the third time another message...

tranquil badge
pliant gulch
slate swan
#

question, how do i toggle allow anyone to mention this role in dpy

pliant gulch
slate swan
#

can someone please answer my previous question

#

if someone were to dm a bot twice, is there any way to change the message the second time someone dms?

#

!d discord.TextChannel.history

unkempt canyonBOT
#

async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.

You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.

Examples

Usage...
slate swan
#

check if the dm channel has a history with a message sent from user

#

thank u sm ill check it out

#
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
#

what would you fill in for the first three dots?

#

the time?

#

or number of messages

#

@slate swan

spring flax
#

you can put message because you are iterating through messages

slate swan
#

wait i am so sorry

#

i want to dm a bot once, get one message. Then the second time i dm it, i want to get a different message

#

is this possible?

tranquil badge
slate swan
#

anyone know how to get the position of the bot in the role hierarchy

tranquil badge
tranquil badge
slate swan
#

i mean to get the position of where the bot sits in the role menu

rancid tendon
#

I'm using Pycord with this code to get any event I want:

event = ctx.guild.get_scheduled_event(int(eventid))
if event is not None:
    users = await event.subscribers(limit=100).flatten()

but I get this error:

in get_scheduled_event_users
    'before': int(before),
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'

https://docs.pycord.dev/en/master/api.html?highlight=event subscribers#discord.ScheduledEvent.subscribers
It doesn't say to specify before...
So do I need to do it now or not???

tough lance
pliant gulch
#

That's why it's blocking all your commands, it's because you aren't handling that part

slate swan
#

Anyone know how to make an inventory for the bot and if you catch anything, it adds it into your inventory

#

How would I remove multiple roles from a member? Would I need to get all roles for each command and then use remove_roles( role1, role2, etc)?

sick birch
#

Though I think mongodb might be easier to model that type of data

sick birch
slate swan
#

Can I get them globally once somehow?

sick birch
#

you can pass in the IDs

slate swan
#

Oh!

sick birch
#

as a list

slate swan
#

Okay thanks

sick birch
#

np

slate swan
#

how to make cooldown

valid galleon
#

how can i get the guild id in the on_guild_remove() event?

unkempt canyonBOT
slate swan
# sick birch you can pass in the IDs

Getting this error

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "/app/plugins/Cordila/cord/bfping-main/bfping.py", line 13, in gaw
    await ctx.author.remove_roles(855877108055015465,723035638357819432,790290355631292467)
  File "/app/.heroku/python/lib/python3.9/site-packages/discord/member.py", line 822, in remove_roles
    await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/app/.heroku/python/lib/python3.9/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: AttributeError: 'int' object has no attribute 'id'

when I tried doing this

await ctx.author.remove_roles(855877108055015465,723035638357819432,790290355631292467)
spring flax
slate swan
spring flax
#

you can get the role obj having the id with this below

#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Examples

Basic usage...
slate swan
#

any its ot but what happens when sql cant find a table?

spring flax
#

you mean what error is raised?

slate swan
#

yeah

#

if any ofc and how would i do an action on it

cobalt jacinth
#

how to check if a message has attachment.

spring flax
unkempt canyonBOT
cobalt jacinth
#

ok thank

pliant gulch
# unkempt canyon

You can also just construct discord.Objects with the IDs of the roles

#

Since remove_roles takes a snowflake

spring flax
slate swan
slate swan
pliant gulch
#

!d discord.Object

unkempt canyonBOT
#

class discord.Object(id)```
Represents a generic Discord object.

The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

x != y Checks if two objects are not equal.

hash(x) Returns the object’s hash.
slate swan
#

ooh thanks!

pliant gulch
spring flax
#

i'm pretty sure he wants to handle that error ^

slate swan
pliant gulch
#

Are you trying to make a default value in your database if it isn't found?

slate swan
slate swan
pliant gulch
#

try-except the error then

slate swan
#

can i really do that🧍‍♂️

spring flax
#

ah it's OperationalError @slate swan

slate swan
#

so the error raises as a traceback in your terminal🧍‍♂️

#

omg its aiosqlite ofc it will raise errors🤦‍♂️

#

sorry guys i had a bit of a brain fartpithink

spring flax
slate swan
#

How do I create channels on command?

#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
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.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
slate swan
stable berry
#

hello

spring flax
#

hello Twirly

stable berry
#
self.FFMPEG_OPTIONS ={'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'. 'options': '-vn'}
#

is the syntax correct

stable berry
stable berry
spring flax
#

!ytdl

unkempt canyonBOT
#

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

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

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

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

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

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

tldr it violates YouTube ToS and we can't help with that

slate swan
stable berry
#

should i not use it ?

stable berry
#

thanks

#

so i am not going to use that

slate swan
#

when I make an on_message function using nextcord, why does it keep on looping?

stable berry
#

what should i use to make a music bot 😅

final iron
#

It's against YouTube's tos

slate swan
stable berry
slate swan
#

this is the code I have rn

slate swan
slate swan
stable berry
#

that means no no for music bot

spring flax
slate swan
#

Oh I see I see

#

you need to check the authors id

#

and no need for the pass

spring flax
#

yeah, i was trying to say the bot's message is a message too

slate swan
#

yeah

stable berry
slate swan
spring flax
#

it doesn't really do anything

slate swan
#

yeah

#

just ignores it

#

how do I check if the message author is a bot?

true moon
slate swan
final iron
slate swan
stable berry
slate swan
unkempt canyonBOT
slate swan
#

returns a bool

final iron
unkempt canyonBOT
#

property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
slate swan
#

that as well

#

same thing lol

stable berry
#

😅

final iron
#

It's an aliase

slate swan
#

yeah

final iron
#

Why do those exist?

#

Consistency?

stable berry
#

i had one more question

slate swan
stable berry
#

like i used member.joined_at for showing the join date and time of when the user joined the server

#

what should i use to show their discord join date

final iron
#

!d discord.User.created_at

unkempt canyonBOT
#

property created_at: datetime```
Returns the user’s creation time in UTC.

This is when the user’s Discord account was created.
stable berry
#

thanks water

final iron
brave tulip
#

how do i add a emoji for presence on my bot

slate swan
brave tulip
#

i tried Activity(), CustomActivity()

#

await bot.change_presence( status = discord.Status.online, activity = discord.Activity(emoji = '🔥', name = str(amount) + "/" + str(max) + " Online!", type = 2))

#

this gives me an error

slate swan
#

!d discord.Activity

unkempt canyonBOT
#

class discord.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

• [`Game`](https://discordpy.readthedocs.io/en/master/api.html#discord.Game "discord.Game")

• [`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
final iron
#

Is using 2 optional arguments in a command hard to implement checks for or am I just doing it wrong

brave tulip
#

it does have emoji wym

slate swan
#

nvm it does give me a sec

ebon island
#

What is the best / most performant Async ODM for MongoDB?

brave tulip
#

i think its not possible

#

it must be a discord thing

#

cause i haven't found a bot with an emoji yet

slate swan
unkempt canyonBOT
#

class discord.PartialEmoji```
Represents a “partial” emoji.

This model will be given in two scenarios:

• “Raw” data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")

• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message.reactions "discord.Message.reactions")...
soft wind
#

guys

#

how i disconnect

#

the bot afterit play

#

mp3 file ???

#

!d

#

!d discord

brave tulip
#

how am i suppose to use this

slate swan
#

dont flood the channel with commands

#

!d discord.VoiceClient.disconnect

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.
slate swan
brave tulip
#

but what arg

slate swan
#

just in the text

brave tulip
#

name = '🔥' gives me an error

slate swan
#

no not in a kwarg but in the text

#

like the status text

brave tulip
#

the activity name?

slate swan
#

yeah

brave tulip
#

i was trying to figure out how to add custom status too

#

it wasn't letting me do a custom one

slate swan
#

in your bot like not a game etc?

brave tulip
#

what

#

yea

#

like for ex

slate swan
#

bots cant

bitter perch
#

Bots can't have custom statuses

brave tulip
#

bruh

#

they can't have emojis then either

slate swan
#

welp im going to go to sleep early gnpithink

stable berry
#

gn

#

how to show random colour

#

like in this statement

slate swan
stable berry
#

in this

#

instead of cyan

slate swan
#

a random embed color

stable berry
#

yes

slate swan
#

!pypi discordheximals

unkempt canyonBOT
slate swan
#

well my module has a random color functionpithink

#

which picks any color from 742 if thats what your looking forjam_cavedude

stable berry
#

yes

#

which can give random colour each time

slate swan
#

yes

slate swan
#

would be how it should look

stable berry
#

thanks

stable berry
slate swan
stable berry
#

ok thanks 😃

slate swan
#

ywpithink

stable berry
slate swan
slate swan
#

ywpithink

#

all the colors are in the github btwpithink

stable berry
#

oki pithink

stable berry
#

thanks

slate swan
#

nppithink

#
@client.listen("on_message")
async def lol(message):
  if message.author != discord.Member.bot:
    await message.channel.send(message.content)
  pass

When I run this code, the message sent keeps on repeating.

#

Is there anything wrong with my code?

#

discord.Member is supposed to represent a Member object, don't just copy paste.

#

.bot returns bool

#

You have a member object in which is message.autor

#
@client.listen("on_message")
async def lol(message):
  if message.author != message.author.bot:
    await message.channel.send(message.content)
  pass

or when I run this code

slate swan
#
if message.author.bot is True:
    return
#

message.author which is a Member object will never be equals a boolean.

#

Just check

if not message.author.bot:
#

I see I see

slate swan
slate swan
#

but why didn't it work when I did if message.author != message.author.bot

#

As I said

slate swan
#

message.author returns a Member object. message.author.bot returns a boolean.

#

I see

#

Member will never ever be equals to a boolean.

#

I see thanks

slate swan
slate swan
#

It was literally all the time

  • Move file in a folder
  • Open file and see the number of lines
  • Write [Name](folder/file.txt) - Lines x
#

So much pain KryptonWriting

#

dang im horrible at readmespithink

boreal osprey
#

im trying to do a on_member_join event inside of a cog but it doesn't send anything

slate swan
#

do you have member intents on?

boreal osprey
#

yes

slate swan
#

and have you loaded the cog and is the event in the cog(indentations)?

boreal osprey
#

yes

slate swan
#

show the cog

boreal osprey
#
@commands.Cog.listener()
async def on_member_join(self,member):
    channel = bot.get_channel(738540358761316439)
    emb=discord.Embed(description = f'Welcome to the server {member.mention}!', color = discord.Colour.random())
    emb.set_thumbnail(url=member.avatar_url)
    await channel.send(embed=emb)
    await member.send("I hope you enjoy your time in this server! :slight_smile:")
slate swan
#

try printing on the event

spring flax
#

self.bot.get_channel

slate swan
#

oh yeah

#

good eye

spring flax
#

it should raise an error, you have an error handler?

boreal osprey
#

but i added self and it work now

patent lark
crisp bloom
#

hey guys, why doesnt this work? I dont know it works sometimes, but now it just stopped working

#

@patent lark

shadow wraith
#

¯_(ツ)_/¯

tender estuary
#

.topic

lament depotBOT
#
**What's one feature you wish more developers had in their bots?**

Suggest more topics here!

maiden fable
#

Uhh bro, this is a topical chat

vale glen
#

Anyone got ideas for my discord bot? It’s based on retrieving data, such as covid-19, weather, etc,

slate swan
#

Retrieve more data. There are probably a multitude of data to gather and display.

slate swan
#

The point of the command is to get a topic, related to Discord bots, to talk about instead of not talking at all or about something not related to Discord bots.

#

So there's absolutely nothing wrong about using it here.

spring flax
#
class EmbedFlags(commands.FlagConverter):
    title : str =None
    description: str```
Can I make this accept either `title/description` **or** `t/d` as a short form?
maiden fable
slate swan
#

The topic command always gets a random topic related to the current channel.

slate swan
#

As py EmbedFlags(title="SmThIng")?

spring flax
# slate swan The class?

Sorry I meant like if i have a command

    @commands.command()
    async def embed(self, ctx, *, flags: EmbedFlags):
        embed = disnake.Embed(title=flags.title if flags.title else '', description=flags.description)
        await ctx.send(embed=embed)

Is it possible that I can do either one of the below
>embed title:[title] description:[description]
or
>embed t:[title] d:[desciption]

maiden fable
#

I don't really think anyone knows about the answer to the question, Diabolical

spring flax
#

ah i guess it's not possible?

#

maybe i can make two flag classes and use union, actually

maiden fable
#

Yea u can try doing that

#

Orrr try doing something like title or t = None

#

Idk this doesn't even make sense

vale wing
spring flax
#

!d discord.ext.commands.FlagConverter

unkempt canyonBOT
#

class discord.ext.commands.FlagConverter```
A converter that allows for a user-friendly flag syntax.

The flags are defined using [**PEP 526**](https://www.python.org/dev/peps/pep-0526) type annotations similar to the [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses "(in Python v3.9)") Python module. For more information on how this converter works, check the appropriate [documentation](https://discordpy.readthedocs.io/en/master/ext/commands/commands.html#ext-commands-flag-converter).

iter(x) Returns an iterator of `(flag_name, flag_value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.

New in version 2.0.
vale wing
#

Ok

spring flax
vale wing
#

@spring flax the only thing I can suggest is to overwrite __getattr__ in your custom class. I am sure the FlagConverter (or its another parent class if it has one) has that overwrited as well, so you could look for example

spring flax
#

yeah that's fine, I just use this as an alternative

@bot.command()
@admin_only()
async def embed(ctx, *, flags : Union[EmbedFlags, ShortEmbedFlags]):
    if isinstance(flags, EmbedFlags):
        embed = disnake.Embed(title=flags.title if flags.title else '', description=flags.description)
        await ctx.send(embed=embed)
    if isinstance(flags, ShortEmbedFlags):
        embed = disnake.Embed(title=flags.t if flags.t else '', description=flags.d)
        await ctx.send(embed=embed)```
#

made two flag classes, one with title/description and one with t/d

vale wing
#

Alright seems legit

tender estuary
#

1 cmd that I have is not working

#

and the reason is literally nothing.

#

The other day it was working not it isnt

spring flax
#

what is it

#

the code

tender estuary
#

let me give here

#
@client.command(aliases=["cmds"])
async def Helpme(ctx):
  embed = discord.Embed(
        title='Help',
        dsecription='These are the commands available for use at the moment.',
        color=0x000000)
  embed.set_author(name="Vincent Viktor")
  embed.add_field(name='v!Pingms',
                    value="Tells you your latency.",
                    inline=True)
  embed.add_field(name="v!meme",
                    value='Have a good laugh, watch some memes.',
                    inline=True)
  embed.add_field(
        name="v!daww",
        value='Happy animals make humans happy, Watch some happy doggos.',
        inline=True)
  embed.add_field(
        name="v!caww",
        value='Happy animals make humans happy, Watch some cute cats.',
        inline=True)
  embed.add_field(
        name="v!paww",
        value='Happy animals make humans happy, Watch some cute pandas.',
        inline=True)
  embed.add_field(name="v!nacc",
                    value='New currency system! Open an account now!',
                    inline=True)
  embed.add_field(name="v!beg",
                    value='Beg to get money... Totally not cool but ok.',
                    inline=True)
  embed.add_field(name="v!bal",
                    value='Check your bank account balance.',
                    inline=True)
  embed.add_field(
        name="v!coinflip",
        value='Feeling lucky? Bet on coin-flipping and earn money.',
        inline=True)
  embed.add_field(name="v!work",
                    value='Earn money the right way, Work for it.',
                    inline=True)
  embed.add_field(name="v!withdraw",
                    value='Withdraw money from your bank account.',
                    inline=True)
  embed.add_field(name="v!deposit",
                    value='Deposit money to your bank account.',
                    inline=True)
  await ctx.send(embed=embed)
#

No reason this won't be working

slate swan
#

You mistyped "description".

tender estuary
#

ohhhh

hot cobalt
#

It sounds like there's a bigger issue here

slate swan
#

You wrote dsecription instead.

hot cobalt
#

Because you should have seen an error

#

So if you didn't that means you're masking it somewhere

tender estuary
#

wait there's another command

hot cobalt
#

And you should fix that as soon as possible

tender estuary
#

I use replit btw it does not show errors

hot cobalt
slate swan
#

Do you have an on_message event by any chance?

hot cobalt
#

I can't say I've used it, but I highly doubt that

tender estuary
#

nvm @slate swan fixed it

slate swan
#

All righty

hot cobalt
#

@tender estuary Do you have error handling anywhere?

tender estuary
#

yep

hot cobalt
#

Send your code for that

slate swan
#

Also I'm pretty sure replit shows errors.

hot cobalt
#

It absolutely should

tender estuary
hot cobalt
#

If it doesn't... well... why would anyone use it

slate swan
tender estuary
#
@client.command(aliases=['wd'])
async def withdraw(ctx, money: int):
    cursor.execute(
        f"SELECT wallet_amt FROM account_table WHERE user_id = {ctx.author.id};"
    )
    db.commit()
    result_w = str(cursor.fetchone())
    result_w = str(result_w).strip('[](),')
    result_w = int(result_w)
    cursor.execute(
        f"SELECT bank_amt FROM account_table WHERE user_id = {ctx.author.id};")
    db.commit()
    result_b = str(cursor.fetchone())
    result_b = str(result_b).strip('[](),')
    result_b = int(result_b)
    if money > result_b:
        embed = discord.Embed(
            title='Don\'t try to oversmart me.',
            description='**You can\'t withdraw money you don\'t have.**',
            color=0xff0000)
        embed.set_footer(text='I mean come on that\'s common sense.')
    elif money <= result_w:
        result_w = result_w + money
        result_b = result_b - money
        cursor.execute(
            f"UPDATE account_table SET bank_amt = {result_b}, wallet_amt = {result_w} WHERE user_id = {ctx.author.id}; "
        )
        db.commit()
        embed = discord.Embed(
            title=f'Account Balance.',
            description=f'**:dollar: Money withdrawn from your bank account.**',
            color=0x00ff05)
        embed.add_field(name=f'Wallet', value=f'{result_w}', inline=True)
        embed.add_field(name=f'Bank', value=f'{result_b}', inline=True)
        await ctx.send(embed=embed)
slate swan
#

You eventually have something not opened or you're not sending errors correctly.

tender estuary
tender estuary
hot cobalt
#

@tender estuary Again, let's fix this error handling

#

Because you're just creating a headache for yourself

slate swan
#

If you have an error handler you eventually blocked remaining errors from showing.

hot cobalt
#

And many more to come

#

Send your error handling code

tender estuary
#
@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        await ctx.send(
            f"No such command, {ctx.author.mention}. type v!cmds for available cmds!"
        )
    elif isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f'Please enter all required arguments.')
    elif isinstance(error, commands.BadArgument):
        await ctx.send(
            f'The command does not take that as the argument, {ctx.author.mention}.'
        )
    elif isinstance(error, commands.BotMissingPermissions):
        await ctx.send(
            f'I miss the permissions to perform that, Make sure to put my role at the top! {ctx.author.mention}.'
        )
    elif isinstance(error, commands.MissingPermissions):
        await ctx.send(
            f'You miss the roles to use this command! {ctx.author.mention}.')
    elif isinstance(error, commands.CommandOnCooldown):
        embed = discord.Embed(
            title=f'Cool down before I burn you up.',
            description=f'Try the command again in {int(error.retry_after)}s.',
            color=0x000000)
        await ctx.send(embed=embed)
placid skiff
slate swan
#

As you can see, all others errors are ignored.

#

You'd want to raise error at the end to make sure they all show.

hot cobalt
#

@tender estuary You should have an else which raises the error

tender estuary
#

let me do it

hot cobalt
#

We can't yet, we need to see the error first

#

Fix up the error handling, run your code again, see if you get an error this time

#

If there isn't one then we can start looking for logic errors

tender estuary
#
else:
      raise error
``` ( ignore indent for now ) correct way?
hot cobalt
#

Yep

tender estuary
#

did not

hot cobalt
#

Did not what?

tender estuary
#

show any error

hot cobalt
#

Right, so must be a logic error assuming you've saved and ran the new code

tender estuary
#

And also to mention

#

whenever I add something to the bot, this is the command which goes null

#

most of the time

#

So, what do I do

#

Do I rewrite the whole command

spring flax
#

what timezone does message.created_at return?

maiden fable
#

Utc

#

!d discord.Message.created_at

unkempt canyonBOT
spring flax
#

oh okay my bad thanks

#

can anyone suggest any unique utility commands? I ran out of ideas

tender estuary
#

I need them as well.

slate swan
#

                embed = discord.Embed(  # Create embed message with current and max online.
                    title="[ZTK Приватный сервер]:\n`Версия 1.16.5`",
                    description=f"[**Онлайн:** `{cur_online.text} / {max_online.text}`] [**Айпи:** `{ip_server.text}`]\n Данные обновляются каждые
5-минут",
                    colour=int("0x2f3136", 16)
                )

?

tawdry perch
#

smth gave None, so it can't use .text

drifting arrow
#

Sup guys

latent veldt
#

hlo

#

anyone know

honest shoal
#

hlo

latent veldt
#

how to deploy my bot on azure

#

pls tell if you know

honest shoal
#

not familiar with azure tbh

latent veldt
#

I am having azure subscription

honest shoal
#

you can google it tho

latent veldt
#

i didn't get any help

#

no idea their

honest shoal
#

also this channel is not realted with hosting

#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
honest shoal
#

its an event

#

its not for command

#

that's an event

#

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

honest shoal
#

why .id

#

look at the first line

#

you want msg2 variable as a message but it is something weird

maiden fable
#

!or-gotcha

unkempt canyonBOT
#

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

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

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

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

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

# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
    print("That's a weird favorite fruit to have.")
gaunt ice
#
  File "main.py", line 31, in <module>
    bot.load_extension("cogs.economy")
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
    self._load_from_module_spec(spec, name)
  File "/opt/virtualenvs/python3/lib/python3.8/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 'cogs.economy' raised an error: SyntaxError: invalid syntax (economy.py, line 151)
#

halpp

bronze prawn
#

Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 140, in on_message
await message.channel.send(embed = embed)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.1.value: This field is required

#

help??

small igloo
#

how to make my bot get the last 1000 voters and send them in an embed

small igloo
zealous dagger
#

how to fix this

small igloo
unkempt canyonBOT
#

Hey @zealous dagger!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

bronze prawn
small igloo
small igloo
zealous dagger
#

HOw to use that

bronze prawn
small igloo
zealous dagger
#

Here you go

#
while True:
      try: # try except is not required but i would recommend using it
        event = await client.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)
        elif label == "Option 3":
          await event.respond(type=InteractionType.ChannelMessageWithSource,ephemeral=False,embed=e3)


      except discord.NotFound:
        print("error.")```
#

Here you go

#

It is showing

#

InteractionType

#

not difined

bronze prawn
zealous dagger
#

where is that located in

bronze prawn
small igloo
zealous dagger
#

OHhhhhh snap

#

I wanted to use select option

small igloo
#

🤷‍♂️

small igloo
zealous dagger
#

Hey

bronze prawn
zealous dagger
#

I wanted to use

#

The select option

#

This

small igloo
# bronze prawn oh

docs linkhttps://devkiki7000.gitbook.io/discord-components/change-log/2.0.0#breaking-changes

zealous dagger
#

I have made the ui

#

But how to respond on the message

small igloo
#

:l both off

vale wing
#

@zealous dagger what library do you use

zealous dagger
vale wing
#

What version

zealous dagger
#

discord_components

#

for the ui

vale wing
#

Why do people like discord_components so much lol

#

It is very inconvenient to use imho

zealous dagger
#

I don't know how to use aany other

small igloo
small igloo
vale wing
zealous dagger
#

OK

#

So

vale wing
#

There are examples in examples folder on github

zealous dagger
#

WHat I have to do

#

for that

small igloo
zealous dagger
small igloo
zealous dagger
#

My code is of 350 lines

small igloo
#

just a reminder that in this channel, slowmode enabled

vale wing
#

The easiest to do right now is to install dpy 2.0, but it is no longer maintained

zealous dagger
#

Ok

#

pip3 install dpy

vale wing
#

Check pins to know how to do that

vale wing
#

They won't fit into the embed tho lol

small igloo
vale wing
#

Need to check their API docs brb

small igloo
small igloo
#

i bet someone will think u r writing a novel

zealous dagger
#

I can't find

vale wing
#

@small igloo do you have any code right now?

zealous dagger
#

there are too many of them

small igloo
small igloo
# vale wing <@828182019841327115> do you have any code right now?
@bot.command()
async def last1000voters(ctx):
    name = ctx.author.id
    if name == 828182019841327115:
        response = requests.get('https://top.gg/api/bots/879000165757890570/votes')
        r = response.json()
        le = len(list(r))
        em = discord.Embed(title="last 1000 voters", description="", colour=ctx.author.color)
        for i in range(le):
            em.add_field(name=str(i + 1), value=f'{r["username"][i]}', inline=False)
        await ctx.send(embed=em)

key error: 'username'