#discord-bots

1 messages · Page 533 of 1

eternal pine
#

yup

slender river
#

so like

import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
    def __init__(self, client):
        self.client = client

#-_-
def setup(client):
    client.load_extension(music, *, package=None)
eternal pine
#

i have run command

boreal ravine
#

i meant that

#

in the main folder

#

also u dont need *, package=none those are kwarg thingies

slender river
#

i was getting some error here it said smtg like "circular import" so ig since it wasnt that many cogs the loop was useless im guessing

boreal ravine
#

i mean it wasnt

#

it still works

#

but more defficient

eternal pine
#

he was online and command doesnt work

#

i tried to add channel

boreal ravine
#

@eternal pine did u do ?help

eternal pine
#

but it is useless

#

ye

boreal ravine
eternal pine
#

i mean to command

#

ctx.channel.send

boreal ravine
#

same thing

eternal pine
slender river
# boreal ravine but more defficient

for now im just trying to make it just work but when i add more cogs for organization etc ill be sure to add the loop back. my b if im bein redundant in the questions

boreal ravine
#

@eternal pine any errors?

eternal pine
#

nope ;/

eternal pine
#

i should remove client.remove_command("help")

#

?

slender river
#

i dont have that line in my bot code so 🤷‍♂️

eternal pine
#

doesnt work still ;/

slender river
eternal pine
#

and this in python

slender river
#

yur using cogs as well right

#

when i was testin my code starting out i just had one main file and now that im testin cogs im getting that error as well

#

so id say smtg wrong with the way its trying to find yur other code

boreal ravine
slate swan
#

Who here is very experienced and can make me a bot for my company

boreal ravine
#

he's using his commands.Bot variable which isnt allowed or nomal in a cog

reef shell
#

man, just say ur instead of yur if you are in that much of hurry

slender river
dapper cobalt
# eternal pine

You most likely have bot.remove_command("help") and did not make another help command. Can you please show your code?

eternal pine
#

yeah i can

boreal ravine
#

@dapper cobalt

eternal pine
#

w8

boreal ravine
#

token

#

remove

eternal pine
#

yeah ik

slender river
gentle gyro
#

Hey

dapper cobalt
eternal pine
#

ye

gentle gyro
#

Is there some API through which you can announce new posts on Instagram?

boreal ravine
#

isn't that illegal

gentle gyro
#

There are a lot of bots which do it for YT uploads

gentle gyro
boreal ravine
#

using 3rd party things to post sonething

boreal ravine
#

onto instagram

slender river
eternal pine
#

uhhh idk i think i will stop coding for this week

gentle gyro
slender river
#

inspirtation

eternal pine
#

but idk what i need to do

slender river
gentle gyro
eternal pine
#

yu XD

dapper cobalt
#

@eternal pine Try rewriting your code.

import discord
from discord.ext import commands

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="?", intents=intents)
bot.remove_command("help")

@bot.command()
async def help(ctx):
  await ctx.send("Help is here!")

bot.run("TOKEN")
eternal pine
#

ok

dapper cobalt
dapper cobalt
eternal pine
#

doesnt work still

boreal ravine
boreal ravine
slender river
#

hey kayle i know yu said to put the bot.load_extension in main but do i need to put smtg else in my cog file?

dapper cobalt
slender river
#

so after i make my class just leave it as is alright

dapper cobalt
#

In case they would need it later on.

devout iris
#

Hey

boreal ravine
#

@devout iris 👋

devout iris
#

How can i set dotenv?

dapper cobalt
#

It'll help you go through cogs.

boreal ravine
eternal pine
slender river
dapper cobalt
boreal ravine
#

Cool.

#

No new questions sadge

dapper cobalt
eternal pine
#

i will ask something in a while XD

boreal ravine
#

Cool.

devout iris
#

Hmmm

dapper cobalt
devout iris
slender river
#

does replit handle import os the same as running it locally would

devout iris
#

A sec

dapper cobalt
slate swan
#

still not dpy

slender river
slate swan
#

hm

devout iris
dapper cobalt
#

First, that was not dpy-related.
Second, I thought that was an error and not a code.

dapper cobalt
tidal hawk
#

How to make it work, so it will wait for reaction add AND reaction remove

#

this way is obv wrong, but just wanted to give a idea

devout iris
dapper cobalt
dapper cobalt
slate swan
#

only with an event and a db

tidal hawk
#

is there some sort of error handler, which will avoid discord.ext.commands.errors.CommandNotFound errors?

eternal pine
#

anyone here have music code?

reef shell
#

no

slender river
reef shell
#

@slate swan use #bot-commands please

river kindle
#

I am creating a mute command but it does not work, as soon as I try to use it the bot gives no response

here the code:

@ commands.has_permissions (manage_messages = True)
async def mute (ctx, member: discord.Member, *, reason = None):

  guild = ctx.guild
  mutedRole = discord.utils.get (guild.roles, name = "Mutato" or 'Muted')

  if not mutedRole:
    mutedRole = await guild.create_role (name = "Mutato")


    for channel in guild.channels:
      await channel.set_permissions (mutedRole, speak = False, send_messages = False, read_messages_history = True, read_messages = False)

  
  await member.add_roles (mutedRole, reason = reason)
  await ctx.send (f "I mutated {member.mention} | Reason: {reason}")
  await member.send (f "You have been changed to {guild.name} | Reason: {reason}")```
slate swan
#

if member.has_perms.manage_roles..., ik its not a thing, but is there anything like this?

hasty iron
#

member.guild_permissions.*

#

replace * with your permission

slate swan
#

make that say @quaint axle.command

#

oops

reef shell
#

!d discord.Member.guild_permissions

unkempt canyonBOT
#

property guild_permissions: discord.permissions.Permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership and the administrator implication.
river kindle
slate swan
lavish zephyr
#

is there a way to make the bot delete messages in bulk even if the messages are older than 14 days?

slate swan
reef shell
#

if it is an attribute of discord.Permissions then yes

slate swan
#

alright

reef shell
#

!d discord.Permissions

unkempt canyonBOT
#

class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.

The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.

Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") similar to [`update()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.update "discord.Permissions.update").
reef shell
#

yeah it will work and will return a boolean value

crystal wind
#

I may sound a little bit too precise with my subject, but is anyone familiar with the discord_components library?

steep estuary
#

if someone send emoji in chat

slender river
#

like dis

steep estuary
#

?

slender river
#
@commands.command()
        async def ping(ctx): 
                await ctx.send(f'pong.  :satellite:  In {(client.latency * 1000)}ms.'
            )
#

":satellite :" bein the emoji

steep estuary
#

no i want to add emoji in that server

#

:/

#

addemoji

#

emojiname

#

emoji

#

and then the emoji should be added in that server

slender river
#

nvr done it but usin logic it would new emoji would be an object and it would once it takes those three parameters it would use the permission and add it in.
theres probably alot of different ways yu could do it 🤷‍♂️

steep estuary
#

:/

#

¯_(ツ)_/¯

#

i didn't understood

reef shell
unkempt canyonBOT
#

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

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

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

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

i have a givelevel command thats add a new level to the user but it says level changed but its not changed in my database im using sqlite3

sick birch
#

Probably shouldn’t be using SQLite3

#

You should be using aiosqlite or asqlite

#

Also make sure you’re commiting after changes

harsh cradle
#

aiosqlite

sick birch
#

Okay, you said SQLite3 so I assume that haha but anyway make sure you actually commit the changes

#

So it actually saves to file

unkempt canyonBOT
#

Hey @eternal pine!

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

eternal pine
#

w8

sick birch
#

Oops wrong channel

#

I thought we were in the other ones lol

#

Nvm then

dawn wasp
#

I didn't find in discord.py docs a way to know who deleted a message using this event (on_message_delete(message))
If anyone solved this before , I would appreciate sharing the solution
Thank you

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @eternal pine until <t:1634147571:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 115 newlines in 10s).

tidal hawk
#

How can I make it so, my bot can run multiple same async funcs at the same time. For example, play 2 blackjacks at the same time?

#

Like how is Mee6 doing it?

reef shell
#

if you have async functions then why can't you run same command multiple times concurrently?

#

have you tried it yet?

tidal hawk
#

ik that async funcs are meant to run concurrently, but it doesn't for some reason

#

let me retry with this gamemode

devout iris
reef shell
#

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

reef shell
#

like time.sleep()

devout iris
tidal hawk
#

Hm okayy

devout iris
tidal hawk
#

like when i clicked that green arrow on below embed, it affected only the first embed

#

okay, now ik it's possible, just need to figure out the right way

still tiger
#

Hello, how can I load cogs recursively?

reef shell
sick birch
#

Unless you cross reference it with the audit log but imo Audit logs suck

reef shell
tidal hawk
#

yep

reef shell
#

show your code snippet

tidal hawk
#

i figured it out, might be problem in check func

#

its large.. very large

slate phoenix
reef shell
#

yeah, you need to check if the reaction.message == the message containing the embed

sick birch
dawn wasp
tidal hawk
#

I had to add : reaction.message.id == self.message_object.id into check func

devout iris
ripe jackal
#

Hello, can someone tell me what to do? I want to make reaction role command. It worked before but something happened with it. This is the command python @client.listen() async def on_raw_reaction_add(payload): message_id = payload.message_id if message_id == 892013850101182474: guild_id = payload.guild_id guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds) if payload.emoji.name == "✅": role = discord.utils.get(guild.roles, id=894206857571356762) await payload.member.add_roles(role)
This is the error: role = discord.utils.get(guild.roles, id=894206857571356762) UnboundLocalError: local variable 'guild' referenced before assignment

reef shell
#

consider using get_guild()

harsh cradle
# sick birch Okay, you said SQLite3 so I assume that haha but anyway make sure you actually c...
    @commands.command()
    async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
        if member == None:
            member = ctx.author
        if ctx.guild == None:
            return
        result = await self.find_or_insert_user(ctx.author)

        user_id, guild_id, xp, level = result
    

        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id,))
        await self.db.commit()
        await ctx.send(f"{member.mention} level changed from {level} to {lvl}")
``` i done that
#

but nothing happing

sick birch
#

are you sure self.db is the databse connection object?

#

you might be trying to do self.bot.db

#

usually people do self.bot inside a cog to access their bot instance

harsh cradle
sick birch
#

create_task doesn't return the value

#

it returns the task

#

this is also probably not the best way to do it

harsh cradle
sick birch
#

you should be creating the connection around the same time you initialize your bot instance

sick birch
#

you can do this:

async def start_bot():
  bot = commands.Bot(...)
  bot.db = await aiosqlite.connect(...)
  await bot.start()

asyncio.run(start_bot())
harsh cradle
#

not into main file

sick birch
#

yes, inside your cog you would do

self.bot = bot
self.db = bot.db
sick birch
#

and close any other things such as aiohttp.ClientSessions there as well

#

this is the recommended method as you don't have memory leaks

harsh cradle
sick birch
#

you don't need it

#

if you connect to the database and attribute it to your bot instance at the start

#

self.bot.db would get you the database connection

harsh cradle
#

"await" allowed only within async functionPylance
(function) connect: (database: str | Path, *, iter_chunk_size=64, loop: AbstractEventLoop | None = None, **kwargs: Any) -> Connection

#
from discord.ext import commands
import config
import discord
import aiosqlite
import asyncio

intents = discord.Intents.default()
intents.presences = True
intents.members = True
bot = commands.Bot(command_prefix='?', intents=intents)

@bot.event
async def on_ready():
    print("Bot is Ready!")

async def start_bot():
  bot = commands.Bot(...)
  bot.db = await aiosqlite.connect(...)
  try:
    await bot.start()
  finally:
    await bot.db.close()
asyncio.run(start_bot())

for ext in ('fun', 'levelling'):
    bot.load_extension(f'cogs.{ext}')

bot.run(config.TOKEN)
``` @sick birch  like that
high flame
sick birch
#

And use Asyncio run to start it

sick birch
#

I didn’t mean it exactly

#

You replace the … with your stuff

#

I only put that there as a placeholder

#

You should move your bot instance to within the Coro

high flame
#

you are starting the bot bot.start() and then bot.run() which is .start()ing already

#

!d discord.Client.run

unkempt canyonBOT
#

run(*args, **kwargs)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login").

Roughly Equivalent to...
sick birch
#

Bot.run is a higher level shortcut method

#

Bot.start is lower level

high flame
#

oh wait

sick birch
#

It gives you more control and is also non blocking

high flame
#

.run() doesn't start()

#

im wrong-

sick birch
#

It does login and connect I think

harsh cradle
#

@sick birch im very sorry cuz i bit stupid but i dont know what did you mean what code i add to main and what i remove and to my leveling cog

sick birch
#

Basically you move your bot instance to a start Coro

#

And inside their you attribute your db instance to your bot

#

Then do .start which is a Coro

#

Inside cogs you can access database like so: self.bot.db

harsh cradle
#

is it bot start low level?

sick birch
#

Asyncio start provides the starting point for your async program

#

It should ideally only be used once

slate swan
#

because it creates and closes the event loop when it finishes

sick birch
#

It is also blocking

#

And as such should be the very last line of code

cloud folio
#

How to get author's role id?

harsh cradle
# sick birch optionally you could implement closing logic ```py async def start_bot(): bot ...

so sholud i delete my whole main code and add this ? btw thats my main code:

from discord.ext import commands
import config
import discord
import aiosqlite
import asyncio

intents = discord.Intents.default()
intents.presences = True
intents.members = True
bot = commands.Bot(command_prefix='?', intents=intents)

@bot.event
async def on_ready():
    print("Bot is Ready!")


for ext in ('fun', 'levelling'):
    bot.load_extension(f'cogs.{ext}')
sick birch
#

No don’t delete your whole code

#

Just add a starting async def function at the bottom

cloud folio
#

How can I get author's role id?

sick birch
#

Call that using asyncio run

#

You should make your bot instance inside there

boreal ravine
#

@cloud folio author's role id?

cloud folio
#

yes

boreal ravine
#

wdym by that

sick birch
#

A member has multiple roles

#

Multiple role IDs

#

Which one do you want

boreal ravine
#

i know

#

but what role

sick birch
#

Ye

cloud folio
#

oh

harsh cradle
cloud folio
#

i didn't thought about that :D

#

I want to check if user has role with specific role id

sick birch
boreal ravine
#

Not likes theres a .author.role.id attribute laying around somewhere..

harsh cradle
boreal ravine
#

😂

sick birch
#

Where is the async start

#

I see your bot instance

#

Which should be inside the async start

cloud folio
#

How can I check if user has specific role (by role id)

harsh cradle
sick birch
harsh cradle
sick birch
#

Command prefix, intents, etc

harsh cradle
#

intents = discord.Intents.default()
intents.presences = True
intents.members = True
bot = commands.Bot(command_prefix='?', intents=intents)

sick birch
#

Yes move that

#

Inside the async start

harsh cradle
sick birch
#

Wdym

harsh cradle
#

when i remove it from top and add in aasync

sick birch
#

I would assume so

#

You won’t have access to bot instance

#

So all bot.events and bot.command will stop working

#

You’ll have to move those into a cog

harsh cradle
sick birch
#

You’ll want to move it inside so you can have more control over the starting event like

#

And so you can attribute your database connection to it

harsh cradle
#

oh

#

you mean move my events thats into main

#

to cog ?

sick birch
sick birch
slate swan
#

role:discord.Role, what is the discord.Role part called

harsh cradle
#

how to add in async

slate swan
harsh cradle
#
from discord.ext import commands
import config
import discord
import aiosqlite
import asyncio

intents = discord.Intents.default()
intents.presences = True
intents.members = True

async def start_bot():
  bot = commands.Bot(command_prefix='?', intents=intents)
  bot.db = await aiosqlite.connect('database.db')
  try:
    await bot.start()
  finally:
    await bot.db.close()
  for ext in ('fun', 'levelling'):
   bot.load_extension(f'cogs.{ext}')
asyncio.run(start_bot())
``` @sick birch  is this right ?
sick birch
#

Looks right

harsh cradle
harsh cradle
#

as i think add bot.run into asnyc to?

sick birch
#

No bot.run at all

#

Use await bot start

harsh cradle
sick birch
#

I mean add_cog

#

Not load_extension

harsh cradle
#

now what should replace in cog

#

@sick birch what about self.bot.loop.create_task(self.connect_database())

summer moth
#

I'm looking for something for me to learn mod.py cogs for music bot and I don't think someone could help me?

sick birch
#

Just self.bot.db for the database

harsh cradle
#

i done all of these

#

nothing is working

sick birch
#

Greet then it should work like normal

#

Wdym by that

harsh cradle
sick birch
#

Well yeah

#

Anything with bot won’t work

#

Bot.events and bot.commands won’t work

reef shell
sick birch
#

Why?

#

Don’t see anything wrong with it

#

Other than not being able to access it outside which can be easily solved with cogs

hasty iron
harsh cradle
#
    @commands.command()
    async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
        if member == None:
            member = ctx.author
        if ctx.guild == None:
            return
        result = await self.find_or_insert_user(ctx.author)

        user_id, guild_id, xp, level = result
    

        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id,))
        await self.db.commit()
        await ctx.send(f"{member.mention} level changed from {level} to {lvl}")
``` i clearly sure this is not a code problem is sql problem i just wanna know why its not editing the database file
reef shell
#

well, not exactly bad, but there is a easy way

sick birch
hasty iron
#

that’s the easiest way

slate swan
#

self.bot.db?

sick birch
#

Self.db isn’t the actual database

#

You were creating a task

#

Which doesn’t return the Coro result

#

Instead returns a task

#

That’s why I suggested attribute the database connection object to your bot instance

#

Within the .start_bot

harsh cradle
# sick birch Because you haven’t configured the database properly

@slate swan @hasty iron
here is the database config:

class Levelling(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.db = None
        self.bot.loop.create_task(self.connect_database())

    async def connect_database(self):
        self.db = await aiosqlite.connect('database.db')
sick birch
#

You could just do run until complete

hasty iron
#

why do you still have that

#

dont you already connect to the db before that

sick birch
#

You shouldn’t be connecting to your database every time

#

Just connect once and save the connection object

hasty iron
#

and instead of doing self.db you would do self.bot.db

sick birch
#

But if you really want self.db you can do self.db = self.bot.db

harsh cradle
sick birch
#

If you want to

hasty iron
#

you can just remove it

sick birch
#

You can delete the whole like

#

Or set it to self.bot.db

harsh cradle
sick birch
#

You don’t need any of that

#

Delete all of that

#

You already connected to the database before

#

Don’t have to do it again

harsh cradle
hasty iron
#

that wouldn’t be related to the function

sick birch
#

Yeah you have to do self.bot.db instead of just self.db

#

So you would have to update it on your code

harsh cradle
#

and it should work?

harsh cradle
#

@sick birch add intents into asnyc or not

sick birch
#

Yes

harsh cradle
#

when i add them

sick birch
#

What errors

harsh cradle
eternal pine
#

what is ffmpeg?

harsh cradle
eternal pine
#

yeah

#

but idk what i need to do with this

harsh cradle
# eternal pine but idk what i need to do with this

FFmpeg is a free and open-source software project consisting of a suite of libraries and programs for handling video, audio, and other multimedia files and streams. At its core is the command-line ffmpeg tool itself, designed for processing of video and audio

sick birch
#

Command line utility for doing stuff with media files

eternal pine
#

okay i have code for music

sick birch
eternal pine
#

but idk why i cant host my bot

sick birch
#

Wdym you can’t host it

harsh cradle
sick birch
#

You have an extra space at the start

slate swan
#

...

harsh cradle
eternal pine
#

nope

#

i just want to host it one time

#

but i cant

sick birch
#

Are you using a VPS?

eternal pine
#

i am opppening cmd

sick birch
#

Elaborate on why you “can’t”

eternal pine
#

then its just crashing

covert igloo
#

Is there an error

eternal pine
#

i can

sick birch
#

That means your computer is screwed up

harsh cradle
#

@sick birch ```py
bot.load_extension(f'cogs.{ext}')

sick birch
#

Yeah

eternal pine
#

idk

#

i can host other bots

sick birch
#

If you can’t open the terminal then you will have to reinstall your operating system but I think you’re not elaborating on what you’re doing

#

Are you just double clicking the .py file?

eternal pine
#

ye

sick birch
#

That happens when there’s an error with the script

eternal pine
#

so problem with the code?

#

i can send it but it has 14k letters xd

sick birch
#

To see what the actual error is load up a terminal, cd to the location, and run Python3 to run it

harsh cradle
#

Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "rank" is not found @sick birch

sick birch
#

Send your rank code

harsh cradle
# sick birch Send your rank code
    @commands.command()
    async def rank(self, ctx: commands.Context, member: discord.Member=None):
        member = member or ctx.author
        cursor = await self.db.cursor()
        user = await self.find_or_insert_user(member)
        user_id, guild_id, xp, level = user
        await cursor.execute("Select Count(*) from users where xp > ? and guild_id=?", (xp, guild_id))
        result = await cursor.fetchone()
        rank = result[0] + 1
        final_xp = self.calculate_xp(level + 1)
        bytes = await self.make_rank_image(member, rank, level, xp, final_xp)
        file = discord.File(bytes, 'rank.png')
        await ctx.send(file=file)
sick birch
#

Are you adding the cog

harsh cradle
#

for ext in ('fun', 'levelling'):

sick birch
#

That’s different

#

That adds the extension not the actual cog

harsh cradle
# sick birch That adds the extension not the actual cog
from discord.ext import commands
import config
import discord
import aiosqlite
import asyncio


async def start_bot():
 intents = discord.Intents.default()
 intents.presences = True
 intents.members = True

 bot = commands.Bot(command_prefix='?', intents=intents)
 bot.db = await aiosqlite.connect('database.db')
 try:
    await bot.start(config.TOKEN)
 finally:
    await bot.db.close()
 for ext in ('fun', 'levelling'):
   bot.load_extension(f'cogs.{ext}')
asyncio.run(start_bot())
sick birch
#

Show me your setup function

sick birch
harsh cradle
harsh cradle
# sick birch .
class Levelling(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.bot.db = None

    async def find_or_insert_user(self, member: discord.Member):
        # user_id, guild_id, xp, level
        cursor = await self.db.cursor()
        await cursor.execute('Select * from users where user_id = ?', (member.id,))
        result = await cursor.fetchone()
        if result is None:
            result = (member.id, member.guild.id, 0, 0)
            await cursor.execute('Insert into users values(?, ?, ?, ?)', result)
            await self.db.commit()
sick birch
#

I mean the setup function

#

Def setup(bot)

#

Every extension should have one

harsh cradle
sick birch
#

Odd that it’s not erroring

#

But you have to have one

harsh cradle
#

to every single

sick birch
#

You do

harsh cradle
#

command

sick birch
#

No

#

To every extension

harsh cradle
#

it just a leveling ex

sick birch
#

Then add one to the leveling file

harsh cradle
#

what is setup func

#

i dont know it

sick birch
#

When you do load_extension it basically calls the setup function on that file

#

That’s all it does

#

The documentation explains it deeper I suggest you read

harsh cradle
#
def setup(bot):
    bot.add_cog(Levelling(bot))
sick birch
#

I see

#

That’s weird then why it ain’t recognizing it

#

What’s the name of your leveling file

harsh cradle
sick birch
#

Is it exactly leveling

sick birch
harsh cradle
sick birch
#

Ah I think I know why

harsh cradle
sick birch
#

You’re loading the cogs after you start the bot

harsh cradle
sick birch
#

It’s not

#

You have to load extensions before starting the bot

sick birch
#

Move it before the bot.start()

harsh cradle
#

bot start in the main file not into cog

eternal pine
#

rn my discord bot is running but i just cant play music

#

ofc i have

#

ffmpeg

sick birch
#

Errors?

#

Code?

eternal pine
#

0

#

14k letters

#

i can send it on pv

sick birch
#

Not reading through that

eternal pine
#

uh

sick birch
#

Errors would be helpful

eternal pine
sick birch
#

?

eternal pine
#

i mean 0 errors

sick birch
#

Can’t see the terminal

eternal pine
#

but commands still doesnt work

#

look at right

sick birch
#

Don’t see anything on the right

eternal pine
#

but i need to send like 20 ss

sick birch
#

Why

#

Impossible to diagnose the error if you don’t provide relevant error info

eternal pine
#

w8

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @eternal pine until <t:1634157097:f> (9 minutes and 59 seconds) (reason: newlines rule: sent 120 newlines in 10s).

vocal magnet
#

!unmute 551398595123871744

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @eternal pine.

vocal magnet
#

Please use a paste service such as this

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

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

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

harsh cradle
eternal pine
#

oh okay

vocal magnet
#

Also, we won't help you with youtube dl here.

harsh cradle
# sick birch correct

Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "d:\project\cogs\levelling.py", line 41, in on_message
result = await self.find_or_insert_user(message.author)
File "d:\project\cogs\levelling.py", line 18, in find_or_insert_user
cursor = await self.db.cursor()
AttributeError: 'Levelling' object has no attribute 'db'
Ignoring exception in command rank:
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "d:\project\cogs\levelling.py", line 204, in rank
cursor = await self.db.cursor()
AttributeError: 'Levelling' object has no attribute 'db'

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

Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\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: 'Levelling' object has no attribute 'db'

#

when i try rank command

#

thats happen

sick birch
#

i know

harsh cradle
sick birch
#

you have to use self.bot.db

#

instead of self.db

slate swan
#

Hello

slate swan
#
@bot.command(pass_context=True)
@commands.has_role("Administrator")
async def buy(ctx, user:discord.Member, gamepass):
    r1 = requests.post(f"https://auth.roblox.com/v1/login", cookies=cookies)
    headers = {'x-csrf-token':r1.headers["x-csrf-token"]}
    r = requests.post(f"https://economy.roblox.com/v1/purchases/products/{gamepass}", headers=headers, cookies=cookies)
    print(r)
#

Hmu if you can Help

slate swan
sick birch
#

which is?

slate swan
#

Idk what error this hol up lemme get the actual error code exactly

sick birch
#

you'll have to elaborate

slate swan
sick birch
#

what gamepass

slate swan
#

And this command can be only used by admins

slate swan
#

Roblox gamepasses have ids that you can enter and locate the pass

smoky marsh
#

hmmm

final iron
#

Fyi requests is blocking

#

Use aiohttp

slate swan
#

It says internal server error

smoky marsh
#

carp

#

carp

final iron
#

You're so funny

smoky marsh
#

ur mom

slate swan
final iron
final iron
slate swan
#

Have never used it

final iron
#

Its a bit different

smoky marsh
#

wut is aysnc

final iron
#

But requests would freeze your bot

slate swan
#

Can you help design this code in my dms because I need this setup by this week

final iron
smoky marsh
#

ok

final iron
smoky marsh
#

gazes is the dude who would drop kick a baby for 2 dollars

#

or maybe 2 cents

slate swan
smoky marsh
#

show code

final iron
slate swan
#

Yea kk

#

Add me and I’ll add u to a go with my other friend we will write code

final iron
#

I said I won't write code for you

#

Also I'll only help you in this discord server

#

No dms

slate swan
#

Yea it’s me and my friend who will write it @final iron

#

We is me and my friend

final iron
#

If you guys need help ask in here or the appropriate channels. I won't be helping anyone in dms

slate swan
#

Kk fine

#

@slate swan

slate swan
#

hi

#

@final iron ya there???

full lily
#

Stop bugging people will ya

final iron
#

I'm here

full lily
#

what do you need help with, g?

final iron
#

Just reading the code

slate swan
#

@slate swan

#

Come back

#

i am here

final iron
#

I'm guessing cookies is defined you just didnt include it

slate swan
#

its defined at the start of the code

final iron
#

Also you don't have to pass context

#

Imma be right back I have to walk my dog

slate swan
#

Ok

slate swan
final iron
#

Just saying I doubt you would be able to find help

#

I'm guessing either the headers are wrong or Roblox has systems in place to prevent this type of thing

#

Error code 500 is a server error

slate swan
#

hm

harsh cradle
#

im already add this

#

self.bot = bot
self.bot.db = None

sick birch
#

clearly didn't

blazing beacon
blazing beacon
#

i know, how do i fix it tho?

reef shell
#

db is a list, right?

blazing beacon
#

no its a

#

hmmwhat is is it gimme a sec

#

its a list

harsh cradle
#

how do i do it then

reef shell
#

like db[0] will return you the first element in that list

blazing beacon
#

oh

#

im not trying to get values

#

but i got it

reef shell
#

alr duck_thumbs

sick birch
#

also don't set it to none

sick birch
#

the bot instance's db attribute

#

which is the database connection object

blazing beacon
reef shell
harsh cradle
sick birch
#

yes the part where you assign bot.db is located in main

harsh cradle
#

now what

sick birch
#

now you can access it like normal

harsh cradle
# sick birch now you can access it like normal
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke        
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\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: 'Levelling' object has no attribute 'db'

sick birch
harsh cradle
sick birch
#

where in your code are you doing it

harsh cradle
sick birch
#

no

#

dms are closed sorry

harsh cradle
#

i dont even know where is the problem

slate swan
#

Dude

#

Learn OOP wtf

#

Also python, learn how to define shit

#

You're redefining bot.db

#

Also you're trying to access self.db which in your class but you never set that attribute

harsh cradle
slate swan
#

By learning python first

#

self.db = bot.db and remove self.bot.db = bot.db

harsh cradle
slate swan
#

You leave it there

#

You can also access it by using self.bot.db

harsh cradle
slate swan
#

Are you sure you're editing and then committing to your db

harsh cradle
# slate swan Are you sure you're editing and then committing to your db
    @commands.command()
    async def givelevel(self, ctx: commands.Context, member: discord.Member=None, *, lvl:int):
        if member == None:
            member = ctx.author
        if ctx.guild == None:
            return
        result = await self.find_or_insert_user(ctx.author)

        user_id, guild_id, xp, level = result
    

        cursor = await self.db.cursor()
        await cursor.execute('Update users set xp=?, level=? where user_id=? and guild_id=?', (xp, lvl, user_id, guild_id,))
        await self.db.commit()
        await ctx.send(f"{member.mention} level changed from {level} to {lvl}")
``` it should be
slate swan
#

Also questions regarding databases go in #databases, i ain't good with those so just wait for someone to answer

harsh cradle
#

ok

#

thanks

sick birch
#

makes sense

#

it should be self.db = self.bot.db

harsh cradle
slate swan
harsh cradle
#

@sick birch its still

#

not even commit the database

final iron
#

Is it possible to edit a message and replace the content with a file?

sick birch
sick birch
vast gale
#

how do y'all mock d.py classes for tests?

solid summit
#

Is there a way of getting the commands args?

strong kettle
#

How i can Check channel permissions (for loop)

sick birch
vast gale
#

so i can some methods that do things?

sick birch
#

you mean subclassing them?

lament flower
#

if i wanted to make a system that tracks points for example whats the best way to go about that - json files or with some kind of database like mongodb?

sick birch
#

though mongo isn't a relational database, and often times, for discord bots specifically, you want relational databases

#

in your case you do want a relation database most likely, mapping each user ID to the number of points they have

lament flower
#

wouldnt that just be basically a json file structure though? i dont really know how databases work and it seems like parsing through a json would work the same as sending a request to a db right?

#

just asking not trying to say im not gonna use a database

sick birch
#

json should NEVER be used as a subsitution for a database

#

sqlite for example has a table-like layout which is probably what you're looking for

#

which is yeah, pretty similar to a json key-value pair

slate swan
#

json is mostly used for static data as I said previously somewhere here because SQL databases are WAY faster when updating and reading

#

and also filtering

sick birch
#

that, and they also don't break down on you like json does

#

json was just not meant for storing and writing data frequently

sick birch
#

and the json library does nothing to alleivate any of those concerns primarily because that's not it's job

slate swan
#

also, dictionary lookups become a pain to read as your "json database" becomes progressively bigger

sick birch
#

more times than not if you're writing to a json file you're doing something wrong

slate swan
#

mongodb is prolly the easiest database

lament flower
#

oh so if i have like a static set of like 100 object types with key value pairs i should use json with that but not if im parsing, reading, writing many objects basically?

sick birch
#

i've heard bad things about pymongo haha

slate swan
#

yes

sick birch
#

yeah, think of json as a config file

slate swan
#

..

sick birch
#

storing your bot token, api tokens, or anything else that doesn't change

#

probably not the best way but you can do that

slate swan
#

not necessarily a config file, but something that rarely gets updated and holds data that rarely changes

sick birch
#

yeah sorry, should've worded that better, json is often used as a config

slate swan
#

is there a way i can make a .env that doesn't show in a github

sick birch
#

.gitignore

slate swan
#

okay i'll do some research

sick birch
#

basically just a file that holds file and folder names github ignores

slate swan
#

i just need it to not show the token or mongodb link

sick birch
#

my gitignore, you can see how it blocks random stuff

slate swan
#

ohh so i just put the file name in there??

sick birch
#

yep

slate swan
#

k

sick birch
#

and when you commit to gh it will ignore it

slate swan
#

can you remind me how to connect my repo to my vscode

civic tree
#

eyo i got questions

sick birch
#

yeah it's the 3rd button from the top on the left

slate swan
lament flower
#

in terms of going into databasing with my discord bot - should that be something i prepped during the initial development (core functionality with code). or is it something i can attach to my bot after i get everything basic done and then need to start working on database information

slate swan
#

its the same as using a module or library

civic tree
#

is there way i can remove my bot messages in DM?

slate swan
#

try mongodb or sqlite3

sick birch
#

aiosqlite*

slate swan
sick birch
#

don't use sqlite for discord bots, blocking

slate swan
#

you use a module/library as a connector which is the way to stablish connections with the database in code other than manually

slate swan
unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
sick birch
#

aiosqlite/asqlite both are good

slate swan
#

How would I go about adding an amount of times a cmd can be used

sick birch
#

permanently?

slate swan
civic tree
#

test gone wrong moment.

sick birch
#

probably photoshop

spare agate
#

does anyone know how to kick a member from the guild? i was trying await member.kick, but its not working

here is my code

@commands.command(aliases= ["expulsar"])
@commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member: discord.Member, reason=None):
        
        if member is ctx.message.author:
            raise SelfMentioned

        if ctx.author.top_role < member.top_role:
            raise OnTop
        
        await member.kick(reason=reason)
sick birch
lament flower
#

and which database is best for doing a database? i dont really like using GUI db stuff. i did mysql years ago and that was alright but i think you have to pay for that and i dont really want to pay...

slate swan
sick birch
#

commands.Cooldown

slate swan
#

postgresql is the fastest iirc

#

now how would I go about All-time

sick birch
#

shows you the tables and the rows and whatnot

sick birch
slate swan
civic tree
sick birch
#

some sort of timer combined with a counter

#

though i don't really see why you would want to do this

slate swan
#

ahh i've checked docks look at limits but haven't seen anything really

#

yea probably going to have to add a counter

lament flower
#

@slate swan what's iirc?

slate swan
#

if I can recall correctly

#

or if I recall correctly

lament flower
#

lol i was like "never heard this terminology" (does google search)

slate swan
#

ik i shouldn't be asking but i really need someone to code with fendi_laugh10 fendi_laugh10

lament flower
#

for my discord bot would it be better to host it myself or is there some kind of cloud service that is recommended for automation so i dont have to host?

spare agate
#

does anyone know how to kick a member from the guild? i was trying await member.kick, but its not working

here is my code

@commands.command(aliases= ["expulsar"])
@commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member: discord.Member, reason=None):
        
        if member is ctx.message.author:
            raise SelfMentioned

        if ctx.author.top_role < member.top_role:
            raise OnTop
        
        await member.kick(reason=reason)
civic tree
spare agate
#

yes

tulip oracle
#

discord.Guild.kick()

#

discord.Member.kick() will do the same

slate swan
#

!d discord.Member.kick

unkempt canyonBOT
#

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

Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
tulip oracle
#

you will need to ban from the server when doing a hackban process

civic tree
#

await member.kick(reason=reason)

tulip oracle
#

rather than member kick

lament flower
#

how come you have your async function tabbed after the constraints?

spare agate
tulip oracle
slate swan
#

how can i load a folder thays inside of a folder

#

as cogs

tulip oracle
#

but i am smelling you pasting in code that you dont understand

spare agate
#

there is no error

#

at the console, i dont know why

lament flower
slate swan
#

i have ./cogs rn

civic tree
# spare agate I am using this one
    @commands.command()
    @commands.has_permissions(kick_members=True)
    async def kick(self, ctx, member: discord.Member, *, reason=None):
            await member.kick(reason=reason)
            await ctx.send(f'Kicked {member.mention}')
slate swan
#

so should i just do ./cogs/functions??

lament flower
slate swan
#

not what i meant

spare agate
#

its diferent discord.User and discord.Member, member its from users from the server

#

i think

civic tree
#

yup

spare agate
#

my code was supposed to kick, but simply dont work

slate phoenix
#

just unindent everything after @commands.has_permissions

#

thats why it doesnt work

spare agate
#

oh

#

no, its not indentation error

lament flower
#

thats what i said earlier @spare agate you shouldnt have indented your async function

slate phoenix
#

this is an indentation error

spare agate
spare agate
#

sorry, my bad

slate phoenix
#

can you post it?

visual island
#

@spare agate are you in a Cog or normal command?

visual island
spare agate
#

im using other commands in this cog, its working fine

#

like ban

#

just kick that doesnt work

lament flower
#

is it permissions error?

spare agate
#

no, the bot is admin

slate phoenix
#

Do you have an error handler that might be why no error is printing?

spare agate
slate swan
#

do an else:

#

else:
member.kick(reason=reason)

lament flower
#

@commands.has_permissions() check does a check to see if the person performing the command has whichever permissions are specified not the bot

spare agate
#

im the owner of the server

#

that i used to test

lilac latch
#

Tf they changed the server logo

lament flower
#

ill copy your code and see if it throws me the same error

lilac latch
#

Pfft how to get track details from user's spotify??

sick birch
#

Spotify activity object

lament flower
#

@spare agate it works for me

spare agate
#

oh

lament flower
#
# kick member
    @commands.command(aliases=['km'], description="kicks member")
    async def kick(self, ctx, member: discord.Member, reason=None):
        await member.kick(reason=reason)
        await ctx.send(f'Kicked {member.mention}')
spare agate
#

so, i dont know why

lament flower
#

hold on i removed permission thing

#

let me add to check

spare agate
#

ok

lament flower
#

ya it still works for me

spare agate
lament flower
#

can you paste the error and just remove your username data

spare agate
#

the problem is, there is no error

sick birch
#

your error handler is probably crappy then

#

the traceback library helps with nice tracebacks

#

traceback.print_exc()

lament flower
#

remove error handling then add error handling after you finish your working prototype

lament flower
#

are you sure you made your bot administrator in the Oauth2 section when you added your bot?

lament flower
#

are you running your file in vscode or just through the command line?

#

or another ide?

spare agate
#

vscode, but i also tried with host online

lament flower
#

if there's no errors occuring when you run it i would add a print check to see if the command is being performed at all. you also need to reload a cog when you update it from the bot, or you could restart the bot just to be sure

sick birch
#

then you're probably not loading it right

lament flower
#

are you reloading your cog?

spare agate
lament flower
spare agate
sick birch
#

huh

lament flower
#

thats super weird dude

sick birch
#

that's uh-

#

can we see your code right now?

spare agate
#

sure

sick birch
#

and that's inside a cog?

lament flower
#

have print run prior to your member kick

spare agate
lament flower
#

if it runs an error prior to print it wont print

sick birch
#

you mean using before_invoke?

spare agate
sick birch
#

global error handler?

spare agate
#

and other commands not related to this one

sick birch
#

do you have on_command_error anywhere?

spare agate
#

with '''

lament flower
#

you have to do a check to see where the error is occurring. what i would do is run a print("success") in each stage of the command so you know where you are having a problem

sick birch
#

mm

#

you sure that's the only one?

spare agate
#

at the end of the code

sick birch
lament flower
#

im saying this. when you invoke your member.kick(reason=reason) if there is an error (thats not showing for some reason) the function will quit before performing any other actions within the function

spare agate
#

i will try rn

lament flower
#

ya

#

if you get no prints at all then theres some kind of issue with the syntax of the function definition

spare agate
#

the error its in the member.kick, not sure what it is

lament flower
#

try removing a reason

spare agate
#

the command cannot execute without a reason, but i already tried to put the reason as None

sick birch
#

looks like it's getting hung up on the kicking

spare agate
sick birch
#

probably has to do with permission issues

lament flower
#

ya im not sure why because it looks fine and thats a copy paste from my code which works

spare agate
#

let me check again

lament flower
patent lark
#

hm.

spare agate
#

lol, for some reason my bot removed his own role

#

sorry for spending your time guys with that

lament flower
#

np

spare agate
#

and thanks with the help

patent lark
# spare agate

you should take the reason kwarg as the rest of the argument, add * before it, because as of now it will just be taken as one word.

spare agate
patent lark
#

👍

brave flint
#

Traceback (most recent call last):

File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2.2\plugins\python-ce\helpers\pydev\pydevd.py", line 1485, in _exec

pydev_imports.execfile(file, globals, locals) # execute the script

File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2.2\plugins\python-ce\helpers\pydev\ pydev imps pydev execfile.py", line 18, in execfile

exec(compile(contents+"\n", file, 'exec'), glob, loc)

#

I got that error when use debugger with my bots, what i should do?

lament flower
#

it looks like it might be a syntax error

brave flint
#

ok thx for info

lament flower
#

exec(compile(contents+"\n", file, 'exec'), glob, loc)

#

did you mean
exec(compile(contents+"\n"+file+'exec'), glob, loc) ?

#

not sure how your compile function works

wraith osprey
#

Wondering if anyone would be able to point me in the right direction. I've setup a command that assigns a role when a user sends it in a channel, then removes it when they use the command again. This is a command that, like some others, are used frequently. As such, I'd like to create a message with an embed that adds and removes names from the message as necessary. I know there's message.edit and I've read a bit about it but I'm unsure how to utilise it to edit the message to add any new names whilst saving the old one(s), if any.

here's my code for the command as it is at the moment:

@client.command(name='absent')
async def absent(ctx, * role: discord.Role):
    channel = client.get_channel(channelid)
    member = ctx.message.author
    role = discord.utils.get(ctx.guild.roles, name="Absentt")

    if role in ctx.author.roles:
        await ctx.send(f'Welcome back {member.mention}!')
        await channel.send(f'{member.mention} has returned; <@&roleid> role removed.')
        await member.remove_roles(role)
    else:
        await ctx.send(f'See you soon {member.mention}!')
        await channel.send(f'{member.mention} has been marked as <@&roleid>.')
        await member.add_roles(role)
brisk fiber
#

what will you do if your list of names exceeds the character limit?

lament flower
#

is the embed always available? or is it a called upon embed?

wraith osprey
#

I suppose there's a couple ways I could go about it, creating the embed once a user sends the command for the first time, and deleting it when there's no names..although that might be more tedious? I think it'd be easier to use the id of a message that contains an embed already

wraith osprey
patent lark
#

do you want to update the embed every time this command-function is called?

wraith osprey
#

yes that's right

patent lark
unborn canopy
#

im trying to fetch an animated emoji but it keeps returning None

#

what do ido

lament flower
#

i think it would be more effective to show the list of members of a role when its requested within an embed that you edit with multiple pages able to be flipped through via emotes rather than a constantly available embed in a channel or something

wraith osprey
patent lark
# wraith osprey yes that's right

you could iterate through the users and check for the role using a for loop, and for every user which has the role, add their name to the embed.

patent lark
wraith osprey
#

thank you both 🙂

patent lark
#

you're welcome

unborn canopy
patent lark
#

if it's returning None, then the bot cannot find the emoji

unborn canopy
#

but the emoji is in the server

patent lark
#

i also dont think making an API call for an emoji is necessary, the emoji should be loaded in the bots cache allowing you to get get_emoji() rather than fetch_emoji()

unborn canopy
#

i dont have to await that do i?

patent lark
#

since it's not an API call, it doesnt need to be awaited

unborn canopy
# patent lark nope

now im getting an error message saying that it can't send an empty message

patent lark
#

let me see the code

unborn canopy
#

i showed u the code that was it

#
@client.command()
async def test(ctx):
    x=client.get_emoji(700698346784030810)
    await ctx.send(x)
#

gtg

patent lark
#

its not finding the emoji i guess.

unborn canopy
#

ok

patent lark
#

maybe it for some reason isn't in the bots cache, but making an API call also returned None so i'm not exactly sure, i would make sure its the correct ID and they are in the same guild.

slate swan
#
import discord, datetime
from discord.ext import commands
from pymongo import MongoClient

cluster = MongoClient("")
db = cluster["Feature"]["guild_data"]


class ModLogs(commands.Cogs):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_guild_event_modlogs_channelcreate(self, channel):
        mod_logs = db.find_one({"guild_id": channel.guild.id})["mod_logs_channel"]
        modlogs = db.find_one({"guild_id": channel.guild.id})["mod_logs"]
        mod_logs_c = self.bot.get_channel(mod_logs)
        guild = channel.guild
        async for entry in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(seconds = 3), action=discord.AuditLogAction.channel_create):
            if modlogs is False:
                return
            elif mod_logs_c is None:
                return
            else:
                embed = discord.Embed(description=f"```Channel Created!```\n`Author:` **{entry.user}**\n`Channel:` {channel.mention}",color=discord.Color.from_rgb(255, 255, 255))
                embed.set_author(name=entry.user,icon_url=entry.user.avatar_url)
                await mod_logs_c.send(embed=embed)
        
    @commands.Cog.listener()
    async def on_guild_event_modlogs_channeldelete(self, channel):
        guild = channel.guild
        mod_logs = db.find_one({"guild_id": guild.id})["mod_logs_channel"]
        modlogs = db.find_one({"guild_id": guild.id})["mod_logs"]
        mod_logs_c = self.bot.get_channel(mod_logs)
        async for entry in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(seconds = 3), action=discord.AuditLogAction.channel_delete):
            if modlogs is False:
                return
            if mod_logs_c is False:
                return
            else:
                embed = discord.Embed(description=f"```Channel Deleted!```\n`Author`: **{entry.user}**\n`Channel:` **{channel}**", color = discord.Colour.from_rgb(255, 255, 255))
                embed.set_author(name=entry.user,icon_url=entry.user.avatar_url)
                await mod_logs_c.send(embed=embed)
    @commands.Cog.listener()
    async def on_guild_event_modlogs_memberbanned(self, member):
        guild = member.guild
        mod_logs = db.find_one({"guild_id": guild.id})["mod_logs_channel"]
        modlogs = db.find_one({"guild_id": guild.id})["mod_logs"]
        mod_logs_c = self.bot.get_channel(mod_logs)
        async for entry in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(seconds = 3), action=discord.AuditLogAction.channel_delete):
            if modlogs is False:
                return
            if mod_logs_c is False:
                return
            else:
                embed = discord.Embed(description=f"```Member Banned!```\n`Author`: **{entry.user}**\n`Member:` **{entry.target}**",color=discord.Colour.from_rgb(255, 255, 255))
                embed.set_author(name=entry.user,icon_url=entry.user.avatar_url)
                await mod_logs_c.send(embed=embed)


def setup(bot):
    bot.add_cog(ModLogs(bot))

final iron
#

Are there any decent library's for buttons?

slate swan
#

discord-components

pale zenith
#

badbad.

final iron
#

Then what would a good one be

pale zenith
#

it has official support for buttons and dropdowns

#

!d discord.ui.Button

unkempt canyonBOT
#

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

New in version 2.0.
slate swan
pale zenith
#

^ these are the docs

final iron
#

How would I update to the dev branch

pale zenith
#

pip install -U git+https://github.com/Rapptz/discord.py

final iron
#

Are there any changes to existing code in this branch

#

Major*

pale zenith
#

yes.

#

but they are not that difficult to fix, don't be overwhelmed by the gist!

#

(it also has support for messages in threads)

final iron
#

What does it mean by None disallowed for argument

pale zenith
#

uhh...

#

i think its just the example

final iron
#

Also since a user with a default pfp returns None, how would I get the specific color of the pfp

pale zenith
#

you can use user.display_avatar

#

that goes in this order: server-avatar -> noramal-avatar -> default(no)-avatar

final iron
#

Any reasons why I shouldn't refractor all my code from member.avatar.url to member.display_avatar?

pale zenith
#

not really

#

unless you specifically want the profile pic

#

and not the server-specific pfp

final iron
#

It doesn't matter in all cases except for my whois command. I would prefer if it gave the actual pfp

slate swan
#
import discord, datetime
from discord.ext import commands
from pymongo import MongoClient

cluster = MongoClient("")
db = cluster["Feature"]["guild_data"]


class ModLogs(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_guild_event_modlogs_channelcreate(self, channel):
        mod_logs = db.find_one({"guild_id": channel.guild.id})["mod_logs_channel"]
        modlogs = db.find_one({"guild_id": channel.guild.id})["mod_logs"]
        mod_logs_c = self.bot.get_channel(mod_logs)
        guild = channel.guild
        async for entry in guild.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(seconds = 3), action=discord.AuditLogAction.channel_create):
            if modlogs is False:
                return
            elif mod_logs_c is None:
                return
            else:
                embed = discord.Embed(description=f"```Channel Created!```\n`Author:` **{entry.user}**\n`Channel:` {channel.mention}",color=discord.Color.from_rgb(255, 255, 255))
                embed.set_author(name=entry.user,icon_url=entry.user.avatar_url)
                await mod_logs_c.send(embed=embed)
``` Error: wont send to channel
final iron
#

Would I just put an if statement saying if the avatar == None use display_avatar

#

I've been using 1.7 for the 3 months ive been creating my bot

pale zenith
final iron
#

yeah so same thing as member = member or ctx.message.author

pale zenith
#

yep

#

its good to update to v2

#

if you see the gh, the repo is archived, so no more updates to it so better update now than later

final iron
#

I know

#

I updated

pale zenith
#

yeah

final iron
#

Is there a mini command I should start with for buttons?

#

Only thing I can think of is a calculator but I think that would be too advanced to start off

pale zenith
#

theres official examples if you want to get a hang of it and mess/modify them - 1 sec

final iron
#

alr

#

Im gonna get to refactoring my code