#discord-bots
1 messages · Page 533 of 1
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)
no
i meant that
in the main folder
also u dont need *, package=none those are kwarg thingies
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
@eternal pine did u do ?help
for?
same thing
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
@eternal pine any errors?
nope ;/
Cool.
i mean just try it out ig
i dont have that line in my bot code so 🤷♂️
doesnt work still ;/
what errors showin up
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
He isnt using cogs
Who here is very experienced and can make me a bot for my company
he's using his commands.Bot variable which isnt allowed or nomal in a cog
man, just say ur instead of yur if you are in that much of hurry
just how i type stuff idek lol
You most likely have bot.remove_command("help") and did not make another help command. Can you please show your code?
yeah i can
@dapper cobalt
w8
"yours" is too much, "ur" is too short, "yer" is too stupid, but yur is just that sweet spot :]
Hey
urs*
@gentle gyro 👋
Rookie question, have you restarted your code afterwards?
ye
Is there some API through which you can announce new posts on Instagram?
isn't that illegal
There are a lot of bots which do it for YT uploads
Is it?
webhooks
using 3rd party things to post sonething
onto instagram
no he means if someone posts smtg then announce what was posted
uhhh idk i think i will stop coding for this week
Not posting it on Instagram...more like 'announcing' new posts on certain channels on discord servers
dont give up or smtg like that
inspirtation
but idk what i need to do
when i get stuck i make a scratch file and test what works and what doesnt and as soon as yu add new code yu will see whats messing it up
Oh from IG to discord?
Yeah
yu XD
@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")
ok
You may check out https://scoopydev.xyz/github?repo=python-discord-bot made by me. I made it to help people create Discord bots using the library disnake.
^^
Edit: I forgot to pass intents in the Bot class.
doesnt work still
don't understand why you need intents though for this
try restarting VSC.
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?
no
just the normal cog class
Just in case.
so after i make my class just leave it as is alright
In case they would need it later on.
yeah?
Hey
@devout iris 👋
How can i set dotenv?
thx
It'll help you go through cogs.
if you dont want it to embed you can put <> around the link
it works tysm ❤️
ayyy
I know about that, but I just forgot. Had school and classes all day!
Wrong reply?
i will ask something in a while XD
Cool.
Hmmm
Not related to Discord bots.
Bro
does replit handle import os the same as running it locally would
A sec
still not dpy
thanks 🕵️♂️
hm
Hmm?
First, that was not dpy-related.
Second, I thought that was an error and not a code.
Your question is related to dotenv, yeah?
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
Yea
Then ask in #python-discussion.
I don't think that is possible.
only with an event and a db
is there some sort of error handler, which will avoid discord.ext.commands.errors.CommandNotFound errors?
anyone here have music code?
no
just look it up on yt
@slate swan use #bot-commands please
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}")```
if member.has_perms.manage_roles..., ik its not a thing, but is there anything like this?
"@ client.command"
make that say @quaint axle.command
oops
!d discord.Member.guild_permissions
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.
no, it is discord that puts spaces
ty
is there a way to make the bot delete messages in bulk even if the messages are older than 14 days?
could discord.Member.guild_permissions.manage_roles work?
if it is an attribute of discord.Permissions then yes
alright
!d discord.Permissions
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").
yeah it will work and will return a boolean value
I may sound a little bit too precise with my subject, but is anyone familiar with the discord_components library?
like dis
?
@commands.command()
async def ping(ctx):
await ctx.send(f'pong. :satellite: In {(client.latency * 1000)}ms.'
)
":satellite :" bein the emoji
no i want to add emoji in that server
:/
addemoji
emojiname
emoji
and then the emoji should be added in that server
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 🤷♂️
!d discord.Guild.create_custom_emoji
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.
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
Probably shouldn’t be using SQLite3
You should be using aiosqlite or asqlite
Also make sure you’re commiting after changes
Okay, you said SQLite3 so I assume that haha but anyway make sure you actually commit the changes
So it actually saves to file
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:
w8
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
: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).
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?
if you have async functions then why can't you run same command multiple times concurrently?
have you tried it yet?
ik that async funcs are meant to run concurrently, but it doesn't for some reason
let me retry with this gamemode
can u send discord.py docs link?
!d discord
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.
that's probably because there is something blocking in your code
like time.sleep()
it's only how to invite
Hm okayy
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
Hello, how can I load cogs recursively?
you can navigate to other stuffs lol
You can’t afaik
Unless you cross reference it with the audit log but imo Audit logs suck
that's not an issue about async
yep
show your code snippet
If the author of the message deleted it you can do message.author but if a mod deleted it for ex you can’t get that from the event
yeah, you need to check if the reaction.message == the message containing the embed
You can’t tell in the first place unless you have perms set up like that
yes I know it's logged in the audit but that's the broblem 😦
figured it out :D
yes that really sucks
I had to add : reaction.message.id == self.message_object.id into check func
i cloudn't find
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
@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
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
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')
``` yeah up the code
create_task doesn't return the value
it returns the task
this is also probably not the best way to do it
im sry i didnt get you im new with aio sqlite
you should be creating the connection around the same time you initialize your bot instance
how
you can do this:
async def start_bot():
bot = commands.Bot(...)
bot.db = await aiosqlite.connect(...)
await bot.start()
asyncio.run(start_bot())
im doing it into cog
not into main file
yes, inside your cog you would do
self.bot = bot
self.db = bot.db
optionally you could implement closing logic
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())
and close any other things such as aiohttp.ClientSessions there as well
this is the recommended method as you don't have memory leaks
class Levelling(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = bot.db
self.bot.loop.create_task(self.connect_database())
async def connect_database(self):
self.db = await aiosqlite.connect('database.db')
``` what about async def connect_database
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
bot = commands.Bot(command_prefix='?', intents=intents)
bot.db = await aiosqlite.connect()
``` i did this but shows error
"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
you can
Yeah put that in a start Coro
And use Asyncio run to start it
@sick birch i did that
your code is wrong
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
you are starting the bot bot.start() and then bot.run() which is .start()ing already
!d discord.Client.run
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...
oh wait
It gives you more control and is also non blocking
It does login and connect I think
@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
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
what is asyncio start for?
is it bot start low level?
Asyncio start provides the starting point for your async program
It should ideally only be used once
because it creates and closes the event loop when it finishes
How to get author's role id?
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}')
How can I get author's role id?
@cloud folio author's role id?
yes
wdym by that
Ye
oh
i already have
bot = commands.Bot(...)
i didn't thought about that :D
I want to check if user has role with specific role id
Where? I don’t see it
Not likes theres a .author.role.id attribute laying around somewhere..
intents = discord.Intents.default()
intents.presences = True
intents.members = True
bot = commands.Bot(command_prefix='?', intents=intents)
😂
Where is the async start
I see your bot instance
Which should be inside the async start
How can I check if user has specific role (by role id)
async def start_bot():
bot = commands.Bot(...) i mean what is bot = commands.bot for
If guild.get_role(id) in member.roles
That’s your bot instance
what i add in it
Command prefix, intents, etc
but i have it in my top of code
intents = discord.Intents.default()
intents.presences = True
intents.members = True
bot = commands.Bot(command_prefix='?', intents=intents)
should i add it into ''
Wdym
im getting errors in my events and commands
when i remove it from top and add in aasync
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
so whats the point i didint get you when you said move the intents and bot prefix inside async
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
but is giving errors and my events well stop working
oh
you mean move my events thats into main
to cog ?
That’s why you put them in a cog
Correct
role:discord.Role, what is the discord.Role part called
i done this but now i cant load my cogs bec no longer bot = commands.bot
how to add in async
class Cogs(commands.Cog):
def init(self, bot):
self.bot = bot
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 ?
Looks right
ok
Load cogs in start bot
as i think add bot.run into asnyc to?
@sick birch yea i add load command into async
ok the main file done
now what should replace in cog
@sick birch what about self.bot.loop.create_task(self.connect_database())
I'm looking for something for me to learn mod.py cogs for music bot and I don't think someone could help me?
Don’t need any of that
Just self.bot.db for the database
ok
i done all of these
nothing is working
it says no command named and my all events stopped
very bad way of constructing a bot instance
Why?
Don’t see anything wrong with it
Other than not being able to access it outside which can be easily solved with cogs
how
@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
well, not exactly bad, but there is a easy way
Because you haven’t configured the database properly
that’s the easiest way
self.bot.db?
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
@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')
You could just do run until complete
You shouldn’t be connecting to your database every time
Just connect once and save the connection object
and instead of doing self.db you would do self.bot.db
But if you really want self.db you can do self.db = self.bot.db
should i edit something in = None
If you want to
you can just remove it
what about
self.bot.loop.create_task(self.connect_database())
async def connect_database(self):
self.db = await aiosqlite.connect('database.db')
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
but if i do agine the async thing you tell me it the whole files well not respond or work
that wouldn’t be related to the function
Yeah you have to do self.bot.db instead of just self.db
So you would have to update it on your code
so i have to delete the loop create task and do the async agine in main file
and it should work?
Mmhm
@sick birch add intents into asnyc or not
Yes
What errors
what is ffmpeg?
it helps you with music bots i think
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
Command line utility for doing stuff with media files
okay i have code for music
Okay but what are the errors though
but idk why i cant host my bot
Wdym you can’t host it
Unexpected indentationPylance
(variable) bot: Bot
You have an extra space at the start
...
you mean you wanna make it 24/7
Are you using a VPS?
i am opppening cmd
Elaborate on why you “can’t”
then its just crashing
Is there an error
i can
That means your computer is screwed up
@sick birch ```py
bot.load_extension(f'cogs.{ext}')
Yeah
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?
ye
That happens when there’s an error with the script
To see what the actual error is load up a terminal, cd to the location, and run Python3 to run it
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "rank" is not found @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)
Are you adding the cog
yeah i add it bot.load_extension(f'cogs.{ext}')
for ext in ('fun', 'levelling'):
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())
Show me your setup function
.
ok
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()
no i dont have that
You do
command
it just a leveling ex
Then add one to the leveling file
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
oh i have it already i didnt saw
def setup(bot):
bot.add_cog(Levelling(bot))
I see
That’s weird then why it ain’t recognizing it
What’s the name of your leveling file
i dont know maybe its asnyc problem
Is it exactly leveling
Doubt
Ah I think I know why
maybe is not a name problem cuz its the same Levelling
You’re loading the cogs after you start the bot
is this normal?
how
Move it before the bot.start()
move what
bot start in the main file not into cog
Not reading through that
uh
Errors would be helpful
?
i mean 0 errors
Can’t see the terminal
Don’t see anything on the right
but i need to send like 20 ss
w8
: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).
!unmute 551398595123871744
:incoming_envelope: :ok_hand: pardoned infraction mute for @eternal pine.
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.
you mean move bot load extensoin upper then bot start?
oh okay
Also, we won't help you with youtube dl here.
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
i know
what you mean
Hello
Can u help me out with something
@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
what exactly is the issue?
This code keeps giving error 500
which is?
Idk what error this hol up lemme get the actual error code exactly
you'll have to elaborate
Basically I want the bot to buy a gamepass that has a specific id when I enter a command
what gamepass
And this command can be only used by admins
Just any roblox gamepass it’s suppose to be for a game system
Roblox gamepasses have ids that you can enter and locate the pass
hmmm
It says internal server error
You're so funny
ur mom
Hmu
?
Damn
wut is aysnc
But requests would freeze your bot
Can you help design this code in my dms because I need this setup by this week
Asynchronous
I'm not going to spoon feed
Well yea but I need some sort of help
show code
I can help you with specific questions but I won't write code for you
I said I won't write code for you
Also I'll only help you in this discord server
No dms
If you guys need help ask in here or the appropriate channels. I won't be helping anyone in dms
There’s my friend answer his question ty
hi
@final iron ya there???
Stop bugging people will ya
I'm here
what do you need help with, g?
Just reading the code
I'm guessing cookies is defined you just didnt include it
its defined at the start of the code
Ok
me?
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
hm
bro
im already add this
self.bot = bot
self.bot.db = None
clearly didn't
i know, how do i fix it tho?
db is a list, right?
then you can access the list elements using index numbers
like db[0] will return you the first element in that list
alr 
maybe you did that somewhere else because your code isn't finding the db attribute
also don't set it to none
set it to what
then
OH I WAS REDEFINING IT
lmao
in the main?
yes the part where you assign bot.db is located in main
self.bot = bot
self.bot.db = bot.db
now what
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'
where are you doing this
what you mean where
where in your code are you doing it
can we dm i will send you the whole leveling cog ok ?
class Levelling(commands.Cog):
def init(self, bot):
self.bot = bot
self.bot.db = bot.db
i dont even know where is the problem
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
Just my give level command is not editing the database and it says level changed and im getting into all of these and i dont know where is the problem
how to set it
what about self.bot
the commands are back to work but it still not commit the database
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
Also questions regarding databases go in #databases, i ain't good with those so just wait for someone to answer
yeah
makes sense
it should be self.db = self.bot.db
ok i will try
i totally didn't say that earlier ikr
Is it possible to edit a message and replace the content with a file?
sorry, i my discord auto scrolls to the latest message and that's just what i saw haha
can you send the updated code with everything we told you to fix?
Is there a way of getting the commands args?
How i can Check channel permissions (for loop)
why would you do that?
so i can some methods that do things?
you mean subclassing them?
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?
defintely a database
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
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
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
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
that, and they also don't break down on you like json does
json was just not meant for storing and writing data frequently
and the json library does nothing to alleivate any of those concerns primarily because that's not it's job
also, dictionary lookups become a pain to read as your "json database" becomes progressively bigger
more times than not if you're writing to a json file you're doing something wrong
mongodb is prolly the easiest database
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?
i've heard bad things about pymongo haha
yes
yeah, think of json as a config file
..
storing your bot token, api tokens, or anything else that doesn't change
probably not the best way but you can do that
not necessarily a config file, but something that rarely gets updated and holds data that rarely changes
yeah sorry, should've worded that better, json is often used as a config
is there a way i can make a .env that doesn't show in a github
.gitignore
okay i'll do some research
basically just a file that holds file and folder names github ignores
i just need it to not show the token or mongodb link
my gitignore, you can see how it blocks random stuff
ohh so i just put the file name in there??
yep
k
and when you commit to gh it will ignore it
can you remind me how to connect my repo to my vscode
eyo i got questions
just ask
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
its the same as using a module or library
doesn't really matter too much
is there way i can remove my bot messages in DM?
try mongodb or sqlite3
mhm
aiosqlite*
rip
don't use sqlite for discord bots, blocking
you use a module/library as a connector which is the way to stablish connections with the database in code other than manually
!d discord.Message.delete
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.
aiosqlite/asqlite both are good
How would I go about adding an amount of times a cmd can be used
permanently?
how'd you make your pfp it's dope
test gone wrong moment.
heh, thanks, i made this over a year ago so don't exactly remember haha
probably photoshop
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)
do you mean all-time or just x times in y seconds?
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...
x times in y sexonds
commands.Cooldown
i like to use the dbbrowser app to view my sqlite for quick testing
shows you the tables and the rows and whatnot
probably store that in a permanent file somewhere, the amount of times it's been used
What if im trying to do it under an event instead of a command. For example setting on_guild_update to a limit of 2
works in DM?
could someone help me pls
probably have to do a more manual approach
some sort of timer combined with a counter
though i don't really see why you would want to do this
ahh i've checked docks look at limits but haven't seen anything really
yea probably going to have to add a counter
@slate swan what's iirc?
lol i was like "never heard this terminology" (does google search)
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?
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)
wdym kick from guild, like kick from the server?
yes
!d discord.Member.kick
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").
you will need to ban from the server when doing a hackban process
await member.kick(reason=reason)
rather than member kick
how come you have your async function tabbed after the constraints?
I am using this one
you need to give errors
but i am smelling you pasting in code that you dont understand
you have to recursively go through the folders you want to check for cogs
i have ./cogs rn
its an indentation error
@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}')
so should i just do ./cogs/functions??
for loop through the files make sure you remove the .py from the end of the parses when you go to load
its almost like that
how you gonna mention a member that ain't in the guild??
not what i meant
when you use discord.member its also user
its diferent discord.User and discord.Member, member its from users from the server
i think
yup
my code was supposed to kick, but simply dont work
thats what i said earlier @spare agate you shouldnt have indented your async function
this is an indentation error
can you post it?
@spare agate are you in a Cog or normal command?
have you load it?
yeah
im using other commands in this cog, its working fine
like ban
just kick that doesnt work
is it permissions error?
no, the bot is admin
Do you have an error handler that might be why no error is printing?
i have error handler, but i already tried to remove and the same result
@commands.has_permissions() check does a check to see if the person performing the command has whichever permissions are specified not the bot
sure
im the owner of the server
that i used to test
Tf they changed the server logo
ill copy your code and see if it throws me the same error
Pfft how to get track details from user's spotify??
Spotify activity object
@spare agate it works for me
oh
# 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}')
so, i dont know why
ok
ya it still works for me
i just copypasted this code, not working
can you paste the error and just remove your username data
the problem is, there is no error
your error handler is probably crappy then
the traceback library helps with nice tracebacks
traceback.print_exc()
remove error handling then add error handling after you finish your working prototype
also tried that
are you sure you made your bot administrator in the Oauth2 section when you added your bot?
yes
are you running your file in vscode or just through the command line?
or another ide?
vscode, but i also tried with host online
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
ok
It doesnt perform the command
then you're probably not loading it right
are you reloading your cog?
ye
this
the other commands from the same cog loads
huh
thats super weird dude
and that's inside a cog?
have print run prior to your member kick
yes
if it runs an error prior to print it wont print
you mean using before_invoke?
there is no error handler, just this command
global error handler?
and other commands not related to this one
do you have on_command_error anywhere?
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
he's saying it's not even running the print
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
ya
if you get no prints at all then theres some kind of issue with the syntax of the function definition
try removing a reason
the command cannot execute without a reason, but i already tried to put the reason as None
looks like it's getting hung up on the kicking
yeah
probably has to do with permission issues
ya im not sure why because it looks fine and thats a copy paste from my code which works
this is what i think
hm.
lol, for some reason my bot removed his own role
sorry for spending your time guys with that
np
and thanks with the help
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.
i already fixed, was the permission of the bot, but thks anyways
👍
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?
it looks like it might be a syntax error
ok thx for info
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
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)
what will you do if your list of names exceeds the character limit?
is the embed always available? or is it a called upon embed?
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
I'm not sure what you mean exactly
do you want to update the embed every time this command-function is called?
yes that's right
if you store users in the embed in which have the role, the embed could eventually exceed discord character limit if there are too many users
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
at this time I don't know if that's something I need to consider, because the character limit is..2000 characters? the above command is an absent command (used for a company in new world) so not many would be using this specific command at once, ideally heh
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.
it's all up to you, if you think its possible that the limit gets exceeded then take an extra step to encounter this, if not, then do as you wish.
show me your code
ahh yeah that makes sense, and yeah good idea regardless to consider using multiple pages, as @lament flower also recommended
thank you both 🙂
you're welcome
@client.command()
async def test(ctx):
x=await bot.fetch_emoji(700698346784030810)
await ctx.send(x)
if it's returning None, then the bot cannot find the emoji
but the emoji is in the server
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()
i dont have to await that do i?
nope
since it's not an API call, it doesnt need to be awaited
now im getting an error message saying that it can't send an empty message
let me see the code
i showed u the code that was it
@client.command()
async def test(ctx):
x=client.get_emoji(700698346784030810)
await ctx.send(x)
gtg
its not finding the emoji i guess.
ok
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.
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))
code from modlogs.py
Are there any decent library's for buttons?
discord-components
badbad.
Then what would a good one be
update to the dev branch of d.py
it has official support for buttons and dropdowns
!d discord.ui.Button
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.
?
^ these are the docs
How would I update to the dev branch
pip install -U git+https://github.com/Rapptz/discord.py
yes.
but they are not that difficult to fix, don't be overwhelmed by the gist!
(it also has support for messages in threads)
What does it mean by None disallowed for argument
Also since a user with a default pfp returns None, how would I get the specific color of the pfp
you can use user.display_avatar
that goes in this order: server-avatar -> noramal-avatar -> default(no)-avatar
Any reasons why I shouldn't refractor all my code from member.avatar.url to member.display_avatar?
not really
unless you specifically want the profile pic
and not the server-specific pfp
It doesn't matter in all cases except for my whois command. I would prefer if it gave the actual pfp
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
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
yeeah something like avatar_url = member.avatar.url or member.default_avatar.url
yeah so same thing as member = member or ctx.message.author
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
yeah
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
theres official examples if you want to get a hang of it and mess/modify them - 1 sec


