#discord-bots
1 messages Β· Page 944 of 1
as you can read: The returned context is not guaranteed to be a valid invocation context, Context.valid must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under invoke().
By either typing it in a command OR by going to the file in explorer and opening the PS or CMD there using the context menu.
In the case of commands, Context.valid is always True. In case of regular messages it would be false
iirc Context.valid just checks if there is an underyling prefix that's valid, and a command attached to it
This is all done via StringView's parsing
nope, if it is true it just means that the context is not a valid candidate to be invoked under invoke()
make an example of a disabled command
it is a command registered in the bot
but it will not trigger the Context.valid
discord/ext/commands/context.py lines 259 to 262
@property
def valid(self) -> bool:
""":class:`βbool`β: Checks if the invocation context is valid to be invoked with."""
return self.prefix is not None and self.command is not None```
π€
help
@slate swan Anyhow i gotta get off to work, there are some smart people here, i recommend going to #βο½how-to-get-help or figure out how paths work inside cmd.
if i make a embed like this:
em = discord.Embed()
do i send it like this?
await ctx.send(em=embed)
or the other way around (embed=em)
by the way, it works after adding this line of code here
embed=em
alr thanks
ok i got it thanks for the help
Nice, now all you need to do is put your AI chatbot implementation under this if statement
So it would only run the AI chatbot if context isn't valid
yes already done that! thanks for the help
Alright nice
Was in the heat of the moment, didn't think clearly enough to use control flow instead of switching the whole process
oh interesting
Reading the entire argument was fun
but it is not printing if the context is valid or not
it raises an error xD
Uh.. yes it is
so it is as i said, he has to make a further check
Read my terminal
@bot.command()
async def register(ctx):
cur.execute("SELECT userid FROM usersdata")
# hito eito cum here
result = cur.fetchall()
for x in result:
num = functools.reduce(lambda N, digit: N * 10 + digit, x)
if num != ctx.author.id:
registerr = "INSERT INTO usersdata (userid, balance, tag) VALUES (%s, %s, %s)"
val = (ctx.author.id, "1000", "JOBBER")
cur.execute(registerr, val)
mydb.commit()
basee = "INSERT INTO stock (userid, auracoin, silver, gold, tesla, tata, reliance, litecoin, dogecoin, tether, ethereum, bitcoin, bullcash) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
val = (ctx.author.id, 1000,0,0,0,0,0,0,0,0,0,0,0,)
cur.execute(basee, val)
mydb.commit()
embed = Embed(title="ACCOUNT CREATED ", description="**SUCCESSFULLY CREATED YOUR ACCOUNT**\nTYPE $profile TO CHECK PROFILE", color=0x09EAF9)
embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar_url)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/957544130077143060/957697600138674196/1071-bull-02.png")
y = datetime.datetime.now()
embed.set_footer(text=f"{y.strftime('%x')} {y.strftime('%X')}")
await ctx.channel.send(embed=embed)
elif num == ctx.author.id:
msg = await ctx.channel.send("**YOU HAVE ALREADY REGISTERED TO BIG BULL**")
asyncio.sleep(5)
await ctx.delete(msg)
my if else statement is not working well
It shows ```py
False
True
True
It actually is
Those were from the three messages I sent
Above the error
It raises the error afterwards
didn't saw
anyone can help me out plzzz i m stuck since 1994 in this code
not sure that discord existed in 1994 D_D
help me bro
if you don't tell us what is the problem... we can't check all your code and know what is wrong with it
let me show you
Just from a quick look from mobile it seems like the indentation is off starting with the embed.set_author
well you should not code in python with your phone anyways xD
at least, you should not code big projects
this is entering data in database even the data is already existing there nd the elif command also work
Right, just pointing out a possible issue that I see
i m not coding python in phone
well of course, probably you have no primary key and no unique value in your table, and you are not checking everywhere if the user is already registered in the database
better, you are taking results from your database but you are adding data by that results
hm
val = (ctx.author.id, "1000", "JOBBER") here you are using ctx.author.id but probably you wanted to use x if result is a list of all discord user id registered in your database
tbh your code is a little mess, i'm not truly understanding what you are doing
consider rewriting the whole block with a fresh mind
uhh help
I just got an error while running my discord bot on replit, its seems like a website
What should I do now
Ive been waiting for 3 hours but still nothing
ahhh pls dont use replit
its because of the shared ip
Hm
Thanks for the recommendation
Try kill 1 in the shell
I see, thanks
A suggestion, use ultimatesrv, completely free hosting with 2gb ram
havent gotten a ratelimit error like that once.
Hm
fun fact: you can earn free upgrades to ur server through giveaways in their discord
So I'm getting this errorpy Failed to Load Extension cogs.eval Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\bot.py", line 791, in _load_from_module_spec spec.loader.exec_module(lib) # type: ignore File "<frozen importlib._bootstrap_external>", line 879, in exec_module File "<frozen importlib._bootstrap_external>", line 1017, in get_code File "<frozen importlib._bootstrap_external>", line 947, in source_to_code File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\eval.py", line 162 async def on_submit(self, interaction: discord.Interaction): ^ TabError: inconsistent use of tabs and spaces in indentationin this part of my code and I'm not really sure why since I've combed through it removing any unneeded tabs https://github.com/SnowyJaguar1034/Zupie/blob/master/bot/cogs/eval.py#L152-L164
bot/cogs/eval.py lines 152 to 164
class Evaluate(discord.ui.Modal, title="Evaluate"):
code = ui.TextInput(
label="What code do you want to evaluate?",
style=discord.TextStyle.paragraph,
placeholder="Type the code you want to evaluate here.",
required=True,
max_length=4000,
default="print('Hello World!')",
)
async def on_submit(self, interaction: discord.Interaction):
await self.evaluate(interaction, self.code.value)
await interaction.response.send_message(f"Processing your code now {interaction.user.mention}", ephemeral=True)```
He did say he combed through removing unneeded tabs
their repo also shows the use of tabs for the method and spaces for the textinput
So is there any noticeable issue with my tabs and spaces that I'm just missing? @supple thorn @hushed galleon
So there's an error handler I have for a command if there is still a cooldown
I want different handling for each command, is there a way to have different handlers for each command?
Yeah?
how 
on_command_error will let you do something when an error is raised in any command
help ?-
okay so I'm using on_command_error
And then checking if the error is a cooldown error, if it is, it responds with a message
But I want to respond with a different message for every different command which has cooldown
make a seperate error handler for every command or just check the command name and use conditionals in a global error handler

Recommended to make different command error handlers
yep someone told me in dms 
you mean make a command handler with isinstance to handle that exception
okay so I manged to fix the error (I think) by the most stupid solution possible, removing the first char of the problem lines, tabbing it out to the furthest outside point then re-tabbing it and adding in the missing char, like how does that solve the issue but it seems to work
cringe
???
tbh i would just go to your ide settings and convert tabs into 4 spaces so it wont be 2 different things
so the error wouldn't be raised
Basically repeating of what I said isnt cool π
cringa
na das real
brad lurking
Also enabling linting should pick up on the mixed usage
Brad is always here
I'll try to not lurk as much, and actually participate lol
yeah def get at least flake8
import sys
import traceback
import lib
from lib.ext import commands
@bot.command()
async def example(ctx, number : int):
pass
@example.error
async def example_error(ctx, error):
if isinstance(error, the_error_to_handle):
pass
else:
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)```This isn't spoon feeding or anything right? Also what is this servers opinion on spoon feeding - not allowed right?
π₯
That's shoving the entire meal down their throat
it's not that spoon-feeding isn't allowed
.format 
we're just against it because it's not the purpose of this server
example_error
if you know what setting that is in VSC do you mind sharing, just searching tabs in the settings brings up a lot of results and I don't want to change something that might break something else
search for indentation
probably in settings and just search indentation
You can't feed a meal dependent upon a single shove of spoon
or can you
depends how big is the spoon
No
bigger than the mouth huh?
wait no

@flat solstice the option is called Tab Size
i just recalled
where we started, where we are now
Depends how big the mouth is
you mean these settings?
this chat is so funny
yes
yep
Yes
π
Well
That's one of many variables 
This is what happens when clowns enter
Haven't seen one of Ashley's uwu examples lately
so you're here
dont say that to Ares he didnt do anything
correct

you want to?
Depends on what the example is
so does tab size = 4 seems correct in the ss? I think I've changed it in the past to fix these indentation errors but they still appear every so often
lmao
Yes
yeah its all correct
uwu website example
Whenever you use that emoji i miss my nitro
π
Just use ppn bro
your nitro, how patriotic
The dpy server has alot of duck emojis
Because all of us are di- ducks
lmao
The chat has gone into peace time talks
Yes
!ot 
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
to hog rider base sergeant?
I should finally subclass for my bot constructor
How can I make my bot online all the time
Hog hq to you cadet
still havent done it?
No too lazy

Trying to pull my smash ultimate game up
What are you using to host
Kirby squishy ball of death
host? nothing
HOG RIDER
Not even self hosting?
played smash on my ds
How is your bot online
Oh you should use one then to keep it online
how?
What do you mean how?
I am por i ply brawlhalla like a pussy
because I cant leave my pc on with the vsc running
You pay for it
There are alot of good options
Use a vps
ok nevermind
Vps or a cheap vps depending if you have spare money
I've been using a Raspberry Pi 2 as a Discord.py bot server, it's worked great for me.
I think some have free tiers i don't know if they are any good tho
Same
Thats also an option
"No, not even Heroku."
Ive also used heroku and my phone
Heroku trash
I tried a Raspberry Pi Zero for hosting, but ran into an issue with a dependency needing x64 instead of x32
this talks about all of the free VPS and how they're not good.
If you are wondering how to do it in your phone you need a phone and termux installed on it this is android only i believe no root required
This is pinned for VPS topics too: #discord-bots message
Yeah, it works surprisingly well, but I'm not leaving my old Galaxy S6 on the charge 24/7 constantly awake, running a Termux loop.
Ye
It's amazing i stopped doing it cause
My python ran into issues
And a friend offered his raspberry Pi to be the host
Completely my fault tho
Yeah, I have two Pi 2s downstairs, only using one right now... really should use the other one, but don't know for what.
You could make a storage server if you got some extra SSDs hdds or hell even CDs lying around
Jellyfin? Sure but like, my music files that are transferred on my phone are 27 GB in size (curse lossless files), and I don't know of anything that can automatically download everything.
So I want to use wait_for to wait for a reaction on a specific message, I know how to do that, but how do I make it so it only waits for 60 seconds or any specified time
A
Buut this is getting offtopic now. Moving on.
Ye
await bot.wait_for(..., timeout=60)
How do i define?
NameError: name 'ctx' is not defined
Show the function
tysm
π
embed = discord.Embed(title="Commands", url="eagea", description="akmewgouiam", color=discord.Color.blue())
if user_message.lower() == '.embed':
await ctx.send(embed=embed)
i dont define
You need to have ctx as an argument in there
async def abc(xyz):
This is like really important to the function
Well it makes the function
where do i put
@bot.command()
async def mycommand(ctx):
Before the like the embed code
Make sure the code is indented
define ctx as the first argument in your function
ctx is from a command invocation right?
my england not very good
can you say it more simple?
ctx must first defined in function as argument
Uh
It should be the first thing the function receives so inside () it should have ctx
async def myfunc(argumentone,argumenttwo):
where do i put this
Thatβs called the signature stealth. 
Bro im just trying to explain in simple terms
Signature is a simple term. You learn it when you learn functions.
Which is bottom level python.
because im confused
async def mycommand(ctx):
embed = discord.Embed(title="Commands", url="M", description="Hello", color=discord.Color.blue())
if user_message.lower() == '.embed':
await ctx.send(embed=embed)```
the code is like this?
You have indented the defining of the function
what means indented
Damn guess i need to relearn python
# not indented code
def foo():
# indented code
# still not indented code
# indented code
You know how the code seems pushed to the right that's called indenting
It's making a dent so python understands that it's where the function begins and ends
You should really learn the basics of python before trying to make a bot
can you suggest me a site or sth where i can learn
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
sorry didnt understood
oh I kinda missunderstood too, you're right
this is my first time trying to make cog can you give me a example
you can only message things subclassed from messageables
examples are
ctx
channel
and on_message_delete has to have a commands.Cog.listener() decorator
class mycog(commands.Cog):
# your code here
this is how a cog is made
so wait
i have already coded so many stuffs in 1file i want to destribute all of them in different files
so do i have to rewrite all codes for each?
where?
above
the on_message_delete
cogs must have decorators since bot is on a different file
yes
instead oc clien.send_message
use message.send()
since client.send_message doesnt work
uh you can probably use the ctrl+f to rename after you copy pasted the code
most of it you have to do by hand
no easy way to do it sadly
someone can tell me how to make a rank system or send me the code directly
i mean as a example
@client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
await ctx.message.delete()```
Transform it
client should be replaced with commands.command()
and?
ye its pretty cool
can i make them in folder too?
cogs?
but i heard discord.py will be closed soon π
yes?
help someone can tell me how to make a rank system or send me the code directly
yo guys can a asyncio event be set multiple times or does it have to be reset somehow
show me a example?
example = asyncio.event()
@bot.command()
async def r():
example.set()
async def a():
await example.wait()
and a would be called multiple times
yeah, u can call it multiple times
well idk for some reason it is working once but after that it isn't and I'm trying to find the issue
asyncio.sleep() not asyncio.event()
try that
youll need a db
ok
but like I don't know how I can do the code
Capital E in asyncio.Event
would that work with indefinite time?
ik I was just kind of typing it
Please help, I can't figure out the error command can't run cursor.execute("SELECT hp FROM economy WHERE userid = ?".format(ctx.author.id, ).fetchone()[0])
do not format your SQL queries
Have you thought of using aiosqlite? It's async, what you're using is not
flexes the helper package I made for economy and ranking and channels and warns databases π
PostgreSQL json like?!
nvm my bad π
@start.error
async def on_start_error(ctx, error):
embed = discord.Embed(
title="Timed Out!",
description="You Have Taken Too Long To Reply. Closing This Session.",
color=0xFF5733,
)
if isinstance(error, asyncio.TimeoutError):
await ctx.channel.send(embed=embed)
You should learn how to code then
Oh hello didnβt know that you were into discord bots π
i have a command called "start", which sends an embed where i use bot.wait_for() to wait for a reaction
no
its just an error handler for commands
Ah
so if you dont react the the embed within 60 seconds
it returns an asyncio.TimeoutError
but i dont get the message sent
Don't make command errors, handle the error inside the command instead
first thing I noticed is that doesn't error need a bracket also isn't it
i dont think so
bot.event and command.error dont need brackets iirc
isnt this more organised tho
Nah
my bot is gonna use bot.wait_for a lot
It's more messy in my opinion
It's just messy
handling all the timeout errors from one spot seems logical
A whole cog wide or a bot wide
oh
Is more logical tbh
i see
Link?
this server was made to help python beginners and theres a rule for this

yeah that was kind of a assholeish thing to do
@client.command()
async def add(ctx, member: discord.Member=None, amount=None):
user = ctx.author
users = await get_bank_data()
members = member
amounts = amount
await open_account(member)
if members == None:
await ctx.send(f"{user.mention}, Please mention someone")
return
if amounts == None:
await ctx.send(f"{user.mention}, Please enter the amount")
return
if amounts < 0:
await ctx.send(f"{user.mention}, Amount must be positive!")
return
users[str(members.id)]["wallet"] += amounts
await ctx.send(f"{user.mention}, You gave {amounts} coins to {members.mention}!")
with open("mainbank.json", "w") as f:
json.dump(users, f)
Can anyoe help me with add coins command?
shouldve pointed them to a learning resource instead
would have been less ruder
yes
Whats wrong with it?
i should appologize
yes
Not working
@karmic valley i am sorry for being rude and should have done better
what error
Define "not working"?
Wait a sec my pc died
what
oh no that was good advice lmao
im using try/except and it works now
nah nah should have been less rude about it
fuck pingedthe wrong person
sorry lad
im doing a bad job trying to appologize
im sorry guys
replit ......
Show your on_command_error
I'm using vsc not replit
I don't think so, replit doesn't have a theme like that
wait
im seeing replit everywhere
sry
where is it?
there's nothing wrong with on_command_error its the issue in code ig
Put time above msg
forget it lol
everyhting is working fine except that code
Isn't time already above msg?
under if statement
No, the isinstance function is above msg not time
and above msg
being both those time and msg under if
the code earlier was already correct, just move time inside the if statement
Now?
umm
yes
now no error neither the command is workig
no problem
Add ```py
else:
import traceback
traceback.print_exc(type(error), error, error.__traceback__) # prints the full traceback, like how d.py does it
ok wait
or just do ```py
raise error
else:
raise error?
!pip PyDcDB
though the updated version is on github
oh that's super cool
lol ty
where's the github?
if not member:
return await ctx.send("no member was mentioned")
if not amount:
return awaait ctx.send("you need to set an amount")
Thanks π
but why make member optional if you are going to reject it as None?
show how you're invoking the command
@leaden plaza
@commands.Cog.listener()
async def on_message(self, message):
if re.fullmatch(rf"<@!?{self.bot.user.id}>", message.content):
embed = discord.Embed(
title="Brrrrr",
description="""
Embed Content
""",
color=ORANGE,
)
embed.set_image(url="https://media.giphy.com/media/igHg5yS08NvCwsvH0Z/giphy.gif")
await message.channel.send(embed=embed)
await self.bot.process_commands(message)
how'd i mess this up :/
you don't need amounts = int(amount) when you can just typehint amount to int
Opps sorry i didn't want to reject it
Remove the process commands
doesnt that let the bot process other stuff tho
Already did but still thanks π
Not required in cogs
yeah listener is like listen
I'm not invoking anything
Just do amount: int in the function
amount is None anyways
Also, show yr code and how u r running the command from discord
nevermind
it isnt sending anything in the chat
here's the error
@client.command()
async def add(ctx, member: discord.Member=None, amount: int=None):
user = ctx.author
users = await get_bank_data()
members = member
amounts = int(amount)
await open_account(member)
if not members:
await ctx.send(f"{user.mention}, Please mention someone")
return
if amounts == None:
await ctx.send(f"{user.mention}, Please enter the amount")
return
if amounts < 0:
await ctx.send(f"{user.mention}, Amount must be positive!")
return
users[str(members.id)]["wallet"] += amounts
await ctx.send(f"{user.mention}, You gave {amounts} coins to {members.mention}!")
with open("mainbank.json", "w") as f:
json.dump(users, f)
``` And here's the code
Why does it connect to the db in every method?
do if amount == None before converting to int
or just typehint to int like hunter said
oh ok
wdym suggest a better way then?
@cold sonnetlike this^^
Connect to the db once and store it in a botvar or smth
then you don't need amounts
import aiosqlite
class A:
async def db(self):
if not hasattr(self, '_db'):
self._db = await aiosqlite.connect(...)
return self._db
and keep the None default values
async def add(ctx, member: discord.Member=None, amount: int=None):
Good thing you changed the code @boreal ravine π
ok wait
haha yes
That if statement was never gonna get executed since u have a function named db already
thanks dude it worked but still if not member command isnt working
@slate swan^^ here
ok wait
though this shouldn't change anything
oh sorry
do your if statements before doing anything with the variables
@slate swan Check issues.
but if it's not specified it should tell the user to mention member
you're trying to do something with nothing before checking if it's nothing
yeah I will, later
can someone tell me how to make the discord bot read only one channel?
lol sorry i'm new to it
no need to be sorry
!d discord.ext.commands.has_role @leaden plaza
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
why should I store data in a Bot Variable when I don't have a Bot Object
what
Dude calm down I didn't even see the source code and I also have the words "or smth" appended for a reason
didnt wanna sound aggressive π
I'm not making a bot lol
uh nothing just a helper library for databases for discord bots lol, I need to fix some stuff
Does anyone know what the best button library is? ,':
your pfp makes me think of porn
What the hell?
thankss
π
in some cases yes, but you do realize disnake is a fork of d.py?
disnake's button syntax is exactly the same as d.py's since it's a fork
yes
why dpy as the best though?
I can't type in the terminal but how can I update my discord.py version?
why cant you type in the terminal?
if its like a host limitation or something, configure your requirements.txt/ poetry that way
+1
slash command freaking everyone lmao
@client.command(aliases=["bal"])
async def balance(ctx, member: discord.Member=None):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
wallet_amt1 = users[str(member.id)]["wallet"]
# bank_amt = users[str(user.id)]["bank"]
em = discord. Embed(
title=f"{ctx.author.name}'s balance")
em.add_field(name="Wallet balance", value=wallet_amt)
em1 = discord. Embed(
title=f"{member.name}'s balance")
em1.add_field(name="Wallet balance", value=wallet_amt1)
#em.add_field(name="Bank balance", value=bank_amt)
if member:
await ctx.send(embed=em1)
if not member:
await ctx.send(embed=em)```
Can anyone tell me what i did wrong?
can u tell me if u got any error?
whenever i'm typing ?bal without mentioning its sending me this error
with mention it's working fine
mind showing your get_bank_data function?
ok wait
alr
same as in the vid prolly
which vid? π
some economy bot vid
Why is this a coroutine function when it doesnβt need to be
ig swastik
LMFAOO
What's wrong here? Why does this not work?
async def on_guild_join(guild):
welcomeMsg = 'Hello and thank you for choosing HangmanBot! Use `hm!help` to get help.'
if guild.system_channel is not None:
await guild.system_channel.send(welcomeMsg)
else:
from random import choice
await choice(guild.text_channels).send(welcomeMsg)
uh why are you importing there
await random.choice(guild.text_channels).send(welcomeMsg)
π
Why doesnt my changeprefix command not work?
and you got the decorator rikzy?
from random import choice
It's only a part of my code
so you do have the @bot.event
Yes
why does my change prefix not work
not only there
and btw just wanna say.. that i tried it.. and in case while doing the random.. IF it chooses a channel in which it doesn't has perm to msg.. it'll return an error
@bot.command()
async def clonechannels(ctx, guild_id):
guild = await bot.fetch_guild(guild_id)
for channel in guild.categories:
await ctx.guild.create_category(name=channel.name)
for channel in guild.channels:
if isinstance(channel,discord.TextChannel):
if channel.category is not None:
category = discord.utils.get(guild.categories, name = channel.category.name)
await ctx.guild.create_text_channel(name=channel.name, category= category)
else:
await ctx.guild.create_text_channel(name = channel.name)
if isinstance(channel, discord.VoiceChannel):
if channel.category is not None:
category = discord.utils.get(guild.categories, name = channel.category.name)
await ctx.guild.create_voice_channel(name = channel.name, category = category)
else:
await ctx.guild.create_voice_channel(name = channel.name)
await ctx.send('done!')``` any idea why it doesnt create any channels? The guild has channels and the bot is in there
@bot.event
async def on_guild_join(guild):
welcomeMsg = 'Hello and thank you for choosing HangmanBot! Use `hm!help` to get help.'
if guild.system_channel is not None:
await guild.system_channel.send(welcomeMsg)
else:
await random.choice(guild.text_channels).send(welcomeMsg)
becasue it doesn't have perm to message in the channel that it choosed by random.choice thing
Ah I understand
you need the deco
yes sir
Do I have to write @bot.event each time when using async def?
it is used for specific events
Unfortunate
which lib you're using btw?
discord py
Yea thats what i'm looking forward to
Is there any way to make it work for now?@slate swan
on_message
on_guild_join
on_member_remove```
are all events, so the on_ is kind of telling you that you need it
uhmm for now? just confirm if the ctx.author.id stored in your json is in format of int or str
I was missing that
@bot.command()
async def clonechannels(ctx, guild_id):
guild = await bot.fetch_guild(guild_id)
for channel in guild.categories:
await ctx.guild.create_category(name=channel.name)
for channel in guild.channels:
if isinstance(channel,discord.TextChannel):
if channel.category is not None:
category = discord.utils.get(guild.categories, name = channel.category.name)
await ctx.guild.create_text_channel(name=channel.name, category= category)
else:
await ctx.guild.create_text_channel(name = channel.name)
if isinstance(channel, discord.VoiceChannel):
if channel.category is not None:
category = discord.utils.get(guild.categories, name = channel.category.name)
await ctx.guild.create_voice_channel(name = channel.name, category = category)
else:
await ctx.guild.create_voice_channel(name = channel.name)
await ctx.send('done!')``` any idea why it doesnt create any channels? The guild has channels and the bot is in both guilds.
str ig
@cold sonnet @slate swan thx
:>
yes its str
show me da json
i wanna run screnn share in vc for 24 hour any idea what should i do cause bot cant
i kinda wanna see it
look its string bro
wait.. u want to screenshare or u want the bot to screenshare?
sorry if i sound dumb lmao
π€ ook...
so what should i do now?
wallet_amt1 = users[str(member.id)]["wallet"]
``` what's `member` there?
discord.Member
ok so ig
in case u don't pass the member parameter
when using the command.. it's taking as None.. becuase you've set its default value as None
It's exactly same
so should i remove none?
eh.. can ya vc? lmao
but if i do it'll throw error of not mentioning member
ahhh
Sorry i can't rn
see make error handler for that
ok thanks bro
:>
.

Does anyone know how to turn an UTC date to secs? Welp im not talking abt unix codes but ye, for example if i did an action like a minute ago it should return 60secs π«
If your bot is public then i recommend u to use database instead of json
<t:1648739880:R>
Thats unix code
π
π yes i was just trying if the code is correct
oh
lmao

wait wait
Does the strftime have something that returns the date but like discord-timestamp ?
use timestamp method @slate swan for datetime.datetime
how can i make the bot check the user account creation date and then if its less than a specific number will do something i tried many things and searched but nothing seems to be working
created_at to get the joined date
No like i meant if there is something like:
%ds
Output:
25
25 is Hours just like the datetime thing
already tried and nothing seems to be working
π
It should workπ₯Ή
idk but for me its not working for some reasons
!d discord.Member.created_at
property created_at```
Equivalent to [`User.created_at`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.created_at "discord.User.created_at")
What does "not working" mean?
well it did show the creation date but does not do the thing "if" its less
And how does your code look like?
Akito seems smart 
ok.. but ig.. for datetime.datetime.. timestamp method should work..
π ** **
jsk is a fantastic tool
fr
i hope they add jsk support for slash commands too.. just like how they mostly support prefix commands
Alr π«tnx
Imma use dat then if it returns unix code i will cry
i'm not sure btw.. just guessing lmao. so don't curse me if it doesnt work lol
show me your explanation first if you have one or a piece of code that mine should be looks like it
you can't use code-blocks in slash commands
π ok wait.. it returns unix code only.. but like.. u can convert it.. π idk how u gonna convert tho
so jsk with slash commands would be awkward
you can convert unix timestamps using datetime
Same >:(
π bro ik that
idk how u gonna convert tho
areee
his question is something else
it's not about getting unix code lmao
Probably timedelta would be best
i have no idea what you're talking about
@slate swan
:'/
he's not asking for unix code
Nvm
just use timedelta
Timedelta

!e
import datetime
print(datetime.datetime.utcnow() - datetime.timedelta(minutes=1))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
2022-03-31 15:49:17.068385
that's what you want, right?
Nope
...

I just found dat on their docs 
I meant examples*
i've an idea
but it's not a good idea/practice imo
:'/
Its ight just share it wit me >:(
Hi so this code https://github.com/SnowyJaguar1034/Zupie/blob/master/bot/cogs/eval.py#L40-L44 is giving me this errorpy Ignoring exception in view <MyMenuPages timeout=60 children=5> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='next_check' id=754948796361736213> row=None>: Traceback (most recent call last): File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ui\view.py", line 364, in _scheduled_task allow = await self.interaction_check(interaction) File "C:\Users\Teagan\Documents\Coding\Zupie\bot\utils\eval.py", line 45, in interaction_check return interaction.user == self.user AttributeError: 'MyMenuPages' object has no attribute 'user'can someone shed some light on why as I've been looking at it for a while now and I'm not really getting anywhere.
we cant see that code btw ^^
oh, weird since it should be a public repo, give me a min
bot/utils/eval.py lines 41 to 45
async def interaction_check(self, interaction):
if isinstance(interaction, commands.Context):
return interaction.user == self.ctx.author
elif isinstance(interaction, Interaction):
return interaction.user == self.user```
indeed is
yeah the fact that @unkempt canyon was able to embed it was a bit f a giveaway
the superclass View doesnt call super().init() so MenuPages wont be initialized by itself
although neither of superclasses define a .user attribute, so you will need to define self.user yourself
yeah I added this https://github.com/SnowyJaguar1034/Zupie/blob/master/bot/utils/eval.py#L27-L37 so that I had both context and interactions covered
bot/utils/eval.py lines 27 to 37
self.ctx = None
self.interaction = None
self.message = None
async def start(self, transaction):
await self._source._prepare_once()
if isinstance(transaction, commands.Context):
self.ctx = transaction
elif isinstance(transaction, Interaction):
self.interaction = transaction
self.message = await self.send_initial_message(transaction, transaction.channel)```
and then I'm doing this in the interactions_check https://github.com/SnowyJaguar1034/Zupie/blob/master/bot/utils/eval.py#L27-L37 and I don't appear to be getting any errors in terminal however I do get this interaction failed when I click a button but I think that's to do with it only having one page
bot/utils/eval.py lines 27 to 37
self.ctx = None
self.interaction = None
self.message = None
async def start(self, transaction):
await self._source._prepare_once()
if isinstance(transaction, commands.Context):
self.ctx = transaction
elif isinstance(transaction, Interaction):
self.interaction = transaction
self.message = await self.send_initial_message(transaction, transaction.channel)```
maybe the interaction check was false? personally i found mixing the menupages implementation with buttons confusing for me
What would be the right way to query the audit logs to retrieve a ban author?
can someone help
!format
if i want ot make a role when my bot joins a server (or when someone with manae bot permissions runs a configuration command perhaps) and then save that role to check f someone has that role (in all servers its in) for commands, hwo would i do that?
your python script shouldnt use spaces or other special characters in its name
do i need to write a persistent database that checks if the guild has a role assigned for this purpose yet, and if not create one? and then reference the database entry for the guild whenever a command is used?
@client.command(pass_context = True)
@has_permissions(mute_members=True)
async def unmute(ctx, user: discord.Member):
role = discord.utils.get(user.server.roles, name="Muted")
embed = discord.Embed(title="{} has been unmuted".format(user.name), color=0xff80ff) # To change the color find a hex color you want and put it after 0x
embed.set_thumbnail(url=user.avatar_url)
await client.remove_roles(user, role)
await ctx.channel.send(embed=embed)
@unmute.error
async def mute_error(error,ctx):
if isinstance(error, MissingPermissions):
embed = discord.Embed(title="You Baka! You are not allowed to do this!", description="You don't have permission to use this command.", color=0xff80ff)
await ctx.channel.send(embed=embed)```
isnt working but its also not erroring
yeah thats a reasonable approach
is it possible to get a role by name?
yea lol
for example i make a role on join called "gamemaster" if no role with that title exists?
and then check role by name?
just do if else
discord.utils.get() is a simple way to do that, although checking by name means the admins dont get any control over the role name and may break it unintentionally
to be fair if they break it unintentionally, the bot should eventually go "hey this command requires this role but it doesnt exist" and i can write a failsafe that creates the role
do you have an on_command_error? and also if you put a print at the start, does it show in the console?
oh wait
your mute_error parameters are flipped
then everyone with the old role needs to get added back
that sounds like a admin problem, not a me problem tbh
Stop using role names and use role ids π
@hushed galleonyeah now it works but the commands arent getting executed like it prints it but then doesnt do anything and im owner of the server and it said im a sussy baka i dont have the permission
only if your behavior is well documented
role ids arent universal smh
cough cough ids are not universal
yo guys how can I block while a value (specific index) in a list is equal to a specific value
dickhead
they are unique and can never be changed
what
Calm down
using bot for multiple servers
they arent universal
hack the framework and change the ids to the same kinda matrix thing here @maiden fable
idk what u mean by "universal"
if i have a bot in three servers, i can make a role when it joins called "test" and that name will be the same in all 3 servers
but each server will have a different role id
Ah that way
the ids are not the same everywhere
hunter's assumption was that universal meant universally unique, and snowflakes are made of both a time and random component so they are unique
ok
can u help with dis?
code?
here
!code π
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Problem about computer generated random is that it isnβt truly βrandomβ
same thing
Thanks
But discord uses the twitter snowflake framework either way as well
And they hash in an internal ID
Yea, it is smth like mix of process ID and process number and utc timestamp and a random int
If you enter the same parameters at runtime it will always generate the same thing
E.g time, etc
Yup, I was partially correct lol
and i will titan shift 32
(Idk much about bits and bytes so no comments)
now can someone pls help me UwU
is there a clever way to check if role with name in guild
i mentioned discord.utils.get()
utils.get(guild.roles, name="")
see if it returns None
hello meh back
Needed u here
jesus christ meh gone
"guild" is not defined
as you described that seems odd if you're server owner but cant pass the check
yes its not only that i did the kick command aswell its written the same but just with kick and yh it like did this

so what's the actual issue
well it's not our place to judge
it didnt actually kick
what's the code
that is a very suspicous bot pfp
@client.command(pass_context = True)
@has_permissions(kick_members=True)
async def kick(ctx, user: discord.Member):
embed = discord.Embed(title="Oni-Chan gave me a kick command!", description="Kicking {}".format(user.name), color=0xff80ff)
embed.set_thumbnail(url=user.avatar_url)
await ctx.channel.send(embed=embed)
await client.kick(user)
@kick.error
async def kick_error(ctx, error):
if isinstance(error, MissingPermissions):
embed = discord.Embed(title="You Baka! You are not allowed to do this!", description="You don't have permission to use this command.", color=0xff80ff)
await ctx.channel.send(embed=embed)
remove pass_context = True
it's ctx.guild.kick
oh i was using old discord docs and then i realised
or you can do user.guild.kick
await ctx.send(embed=embed) is enough
will that automatically kick the user aswell
also you should handle your missingpermissions errors globally
instead of only for one command
no we both told you to use ctx.guild.kick instead of client.kick
u said await ... is enough but yh
yes await
and the send one is a different thing that's using one additional unnecessary attribute
and we just don't like to see it
memory loss
i mean it doesn't factually make a difference
ctx.send is just a pointer to ctx.channel.send
unspeedy
@bot.command()
@commands.has_any_role(692760082085183519, 940008547993927691, 863878825376743475, 902292952381001779, 863879069253894166, 902292952381001779, 863879304110276668, 940008547993927691)
async def ΠΏΡΠ΅Π΄(ctx, member: discord.Member = None, *, reason = None):
print(45)
cursor.execute("""CREATE TABLE IF NOT EXISTS warning(guild_id BIGINT, user_id BIGINT, warn INT, count INT, moderator_id BIGINT, reasons VARCHAR)""")
base.commit()
print(1)
warnings = cursor.execute("SELECT * FROM warning WHERE user_id = ?", (member.id,)).fetchone()
print("ΡΠ°Π±ΠΎΡΠ°Π΅Ρ")
if member is None:
await ctx.send("ΠΡΠ±Π΅ΡΠΈΡΠ΅ ΡΡΠ°ΡΡΠ½ΠΈΠΊΠ°")
return
if reason is None:
try:
cursor.execute('INSERT INTO warning(guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1,ctx.author.id,'ΠΡΡΡΡΡΡΠ²ΡΠ΅Ρ'))
base.commit()
except Exception as e:
print(repr(e))
print(2222)
cursor.execute(f'UPDATE warning SET warn = {warnings[2] + 1} WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** ΠΡΠ΄Π°Π» ΠΏΡΠ΅Π΄ΡΠΏΡΠ΅ΠΆΠ΄Π΅Π½ΠΈΠ΅ # {member} (ΡΠ»ΡΡΠ°ΠΉ # )")
else:
cursor.execute('INSERT INTO warning (guild_id, user_id, warn, count, moderator_id, reasons) VALUES(?, ?, ?, ?, ?, ?)', (ctx.guild.id,member.id,0,1, ctx.author.id, reason))
base.commit()
cursor.execute(f'UPDATE warning SET warn = {warnings[2] + 1} WHERE user_id = ? AND guild_id = ?', (member.id, ctx.guild.id))
base.commit()
await ctx.send(f"**{ctx.author.name}** ΠΡΠ΄Π°Π» ΠΏΡΠ΅Π΄ΡΠΏΡΠ΅ΠΆΠ΄Π΅Π½ΠΈΠ΅ # {member}, ΠΏΡΠΈΡΠΈΠ½Π° {reason}. (ΡΠ»ΡΡΠ°ΠΉ # )")
error: TypeError: 'NoneType' object is not subscriptable
If a person is not in the database, then at first he will give an error, after a reboot, it will work, how to fix it?
lol why is it bugging you it ends up in the same place
if you care about the... single second it takes to type .channel. ..sure
python functions can't have special characters
that's a start
._.
lol
What?
._.
russian function = special characters
._.
wzr is the command invoked?
if the person is not in the database, then no, there is an error, after restarting the bot, everything works
._. indeed
can i pass this the name of a role?
no
grab the specific role using utils.get
@client.slash_command(
name="init__util_",
description="run this once when you add the bot"
)
async def initutil(ctx):
if disnake.utils.get(ctx.guild.roles, name="Gamemaster") == None:
await ctx.guild.create_role(name="Gamemaster",reason="init__util_/created_role")
await ctx.author.add_roles()
what is that lone await doing there
now I'm wondering how getting a messageable with ctx's attribute to use send on it and using the inherited send in ctx doesn't make a difference
what?
nvm, discord wonky format

I lost half my braincells tryna comprehend what u mean...
uh, you're supposed to assign the role created a variable
hehe that was the whole point
lmfao
@client.slash_command(
name="init__util_",
description="run this once when you add the bot"
)
async def initutil(ctx):
if disnake.utils.get(ctx.guild.roles, name="Gamemaster") == None:
role = await ctx.guild.create_role(name="Gamemaster",reason="init__util_/created_role")
await ctx.author.add_roles(role)```
there ya go
np
ensures that the cached roles are always ignored
so for example, if a role isn't in the cache the operation could fail
so it will always use an api fetch request to get them
just leave it at default
we don't exactly know what's in your database
that sounds like its for complex stuff
if not disnake.utils.get(...):
@client.command()
@has_permissions(mute_members=True)
async def mute(ctx, user: discord.Member):
role = discord.utils.get(user.server.roles, name="Muted")
embed = discord.Embed(title="{} has been muted!".format(user.name), description="When the user needs unmuting do !unmute @user!" , color=0xff80ff) # To change the color find a hex color you want and put it after 0x
embed.set_thumbnail(url=user.avatar_url)
await ctx.guild.add_roles(user, role)
await ctx.channel.send(embed=embed)
@mute.error
async def unmute_error(ctx, error):
if isinstance(error, MissingPermissions):
embed = discord.Embed(title="You Baka! You are not allowed to do this!", description="You don't have permission to use this command, if you do have the permission to execute this command make sure there is a Muted Role in your server!", color=0xff80ff)
await ctx.channel.send(embed=embed)
why is this returning to the MissingPermissions error even though i am Owner of the server?
but I was much sooner already suspicious of why you're doing base.commit() instead of cursor
tell that to them not me, i just fixed the thing they requested...
perhaps the bot oesnt have the permissions
what the heck is mute_members perm
maybe I'm just dumb for that lib
The bot doesn't have permission to give it to you.
no bot is top of list
isnt if not the same as if !
i mean in your developer portal
regardless of whatever permissions the bot has, no operationsare allowed to the server owner
!d discord.Permissions.mute_members
Returns True if a user can mute other users.
What the
mute_members should be for the new timeout feature
That's for voice channels.
how did you not know that was a thing??
ohh
ooh yeah thats for voice channels
btw can bots not apply timeouts yet?
Its been ages since I have coded discord bots, sorry
can anyone help
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
forgot self
Yes
unless you want to make it so muted users can still access a specific channel
ye i want it role based
no not really, if you want in server mute appeals they are useful
every class's functions' parameters have to start with self
i find that kinda stupid
π€· Useless API calls for the role mute command
@client.slash_command(
name="init__util_",
description="run this once when you add the bot"
)
async def initutil(ctx):
if disnake.utils.get(ctx.guild.roles, name="Gamemaster") == None:
role = await ctx.guild.create_role(name="Gamemaster",reason="init__util_/created_role")
await ctx.author.add_roles(role,reason="init__util_/assigned_role")
but uh, whatever, it's your server
Well imho, u should instead make the bot DM the person, the appeal form after timing them out
does this look proper?
Mute role is higher than member role as member role in showing i want to present them to the members as clowns
some servers do mute appeals as a conversation not a form
why don't u do it on_guild_join
if not disnake.utils.get() ahem ahem
then again, i don't think a mute is something that should be carried out for long enough that it is required to have an appeal
Ah well modmail threads ftw!
doesn't that raise an error if it fails actually?
hi guys, on what ide do you code ?
vscode
vsc
that would only fire off if the bot is online when it joins and wouldnt fire off on servers its already in?
Wym
why does it have to
if disnake.utils.get(β¦) is None is computationally faster
oh
And itβs convention
nice thank you very much
really?
oh my bad
ah made a typo with indentation
typo with indent
It has to check many things instead of one thing
Ah
If that makes sense, as your only looking for either a truthy value or a non truthy value
Like it gotta check empty list, None and stuff?
So it has to check more things yep
role can be undefined
what?
Yea
undefined as in?
as in undefined
Lol imagine if the if statement is never triggered
NameError: name role is not defined
== none is faster in this case especially becasue uitils.get resturns None
Not a big issue but you should be using is not ==
is
ah dmamit
oh yeah
is ther ea difference between is and ==
andy is here to explain u the CPython's internal workings π
== slower?
Read my above messages
meh
lmao
Are there any examples on using a message ID in a command to edit an embed field?




