#discord-bots
1 messages · Page 1106 of 1
cursor.execute(f'SELECT * FROM warns WHERE guild_id = {ctx.author.guild.id} and user_id = {member.id}')
here youre referencing member to be a member object which if its not in this case you dont pass the argument it would be None and the NoneType class has no such attribute so you must add a check to make the member argument always a member object so just do this before that line py member = member or ctx.author
oh thanks
its thats for me ?
no its for Freqqu aka Wojtaz
your error is just a reference of a attribute that hasnt been set yet
ok bc i tel lyou that i alr have it in my code
`if member is None: member = ctx.author
member = member or ctx.author`
what reference ?
Bot.db was referenced before the attribute was set
it dont work
thats not very descriptive is it?
ok thanks, fixed it
https://paste.pythondiscord.com/kutacariru Hello, with this code i have this error, idk how to fix it, thanks for helping
You're using sqlite3 which doesn't support async, and by extension doesn't support things like async with
oh okkk
to doesnt make any error, what should i replace async with ?
cursor.execute ?
what ?
You're using sqlite3 as if it were aiosqlite, and using await for statements that don't support it
So you need to remove sqlite3, install aiosqlite, and completely migrate over
Also you're making a database connection in on_ready() which is a terrible idea
This reminds me why I hate using python connectors 😄
aiosqlite is way better ?
No, aiosqlite is the same as sqlite3, except it's asynchronous
They're 2 versions of the same thing
ok i'll inquire
@sick birch just to know, if i move to aiosqlite, my previous code of sqlite3 will be unfonctionnable ?
That's correct
ok and this give me a lot of error
That was only a temporary solution, switch over to aiosqlite
i m do it
@discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title = "Договор об устройстве на шахту SK",
color= 0x19ff19
)
embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True)
embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
embed.add_field(name=" ", value= " ", inline=False)
embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True)
embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)
await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.author.id))
Dear what should be written in iron vacancies class. to pass the ID of the button clicker?
It's interaction.user.id
i have this error now, do you want the code ?
Switching over to aiosqlite is going to require a good bit of rewriting most things related to your database
Create your db instance inside your setup_hook
Create one by subclassing discord.ext.commands.Bot
@discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title = "Договор об устройстве на шахту SK",
color= 0x19ff19
)
embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True)
embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
embed.add_field(name=" ", value= " ", inline=False)
embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True)
embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)
await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.user.id))
class vacancies_iron(discord.ui.View):
def __init__(self, id):
super().__init__()
self.id = id
@discord.ui.button( label = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.edit_message(view=self)
Bind it to your bot instance (self, inside the subclass) and you should be good
Can't have empty field name/value
Maybe I wrote something wrong in another class?
Get rid of the field with no name and no value
Invisible symbol. it works
https://paste.pythondiscord.com/bilidureze i have this
async def initialize():
await bot.wait_until_ready()
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute(
"CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
``` i put this in my main.py
If I remove them it writes an error. I'd rather leave them with an invisible symbol. however, with him, the error is still the one on top. I probably need to transfer something in the second class just now?
I need it to make the second line. without it 3 in one line 1 in the second. or 2 in one 1 in the second and 4 in the 3rd line
I'm not understanding
well, what's your current attempt? have you tried using embed visualizers?
seems like you're trying to add an empty field just to make sure the next field is on a new line
@sick birchOh it worked. I just thought it wasn't related to a mistake sorry I should have heard it right away. I entered \u200b instead of emptiness
yeah that works
Though i'd stay away from those whitespace characters as they tend to be finnicky and look weird on different devices
Yes, I just tried it and it worked)
could someone help me out with slash commands please
@discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title = "Договор об устройстве на шахту SK",
color= 0x19ff19
)
embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True)
embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
embed.add_field(name="\u200b", value= "\u200b", inline=False)
embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True)
embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)
await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.user.id))
@commands.command(aliases = ["Вакансии", "вакансии"])
async def vacancies(self, ctx: commands.Context):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
embed.set_image(url='attachment://image.png')
await ctx.send(file = file1, embed = embed, view=vacancies(ctx.author.id))
And can you tell me how to remove the image after pressing the button?
Please
can someone help me please ? this is my code https://paste.pythondiscord.com/bilidureze
on_message is an event, not a command
and error says it all, make sure you have bot.db defined in your main file or whatever
@commands.Cog.listener()
async def on_ready(self):
db = aiosqlite.connect("expData.db")
self.bot.db = aiosqlite.connect("expData.db")
await self.bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
print("DB EXP is Online | Provisoire Message")
``` now i have this error
don't do shit in on_ready
Especially not this
also, connecting in aiosqlite is async if I'm not mistaken
what should i do ?
See my earlier message: <#discord-bots message>
async def initialize():
await bot.wait_until_ready()
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
``` it is good ?
If you're not on v2 I personally prefer this method:
async def main():
bot = commands.Bot(...)
try:
# initialize anything else here
bot.db = ...
await bot.start()
finally:
# cleanup tasks
asyncio.run(main())
ok
you can....
and if im in a cog ? thats the same ?
you don't want to wait until the bot is ready ofc.
preferably, you want to connection to be made BEFORE the bot is even ready 😉
Shouldn't be. It should be at the very bottom of your main file, and starts your entire bot
ok i see
ok i try this
why defining a bot inside the main function though? and you shouldnt be doing anything after start iirc
Ah yeah true, do the startup before
@discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title = "Договор об устройстве на шахту SK",
color= 0x19ff19
)
embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True)
embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
embed.add_field(name="\u200b", value= "\u200b", inline=False)
embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True)
embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)
await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.user.id))
@commands.command(aliases = ["Вакансии", "вакансии"])
async def vacancies(self, ctx: commands.Context):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
embed.set_image(url='attachment://image.png')
await ctx.send(file = file1, embed = embed, view=vacancies(ctx.author.id))
tell me Please how to remove the image after pressing the button?
it'a better to use a setup_hook though
it just looks cleaner
~on v2
edit message with file=None
❤️
start is a v2 method too, so I thought we were considering that...my bad
is it?
!d discord.Client.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect").
weird
Nice, fast answer
someone in dpy told me that it's a 2.0 feature fml
FORGIVE
welcome
await interaction.response.edit_message(file = None, embed = embed, view=vacancies_iron(interaction.user.id))
Oops, I wrote it wrong(((
i m lost
Ah I believe it's attachments=[]
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
You're not actually calling it
Use asyncio.run() to call it and replace bot.run(...) with await bot.start(...)
you have to call the initialize function...
someone has a link to an example or template to pull a twitch stream info and post it on discord as a "going live now" notification?
that's 2 steps
by info i mean like category (game), stream title etc
See if twitch has an API for that
maybe the imbedded image of the game / category being played too
i have a question, why does discord ascii colored text look trash on mobile?
Discord code blocks in general look garbage on mobile
@sick birch@slate swan I love you😍
they do, but i thought i could grab those from the discord.ativitytype thing
bot.db = asyncio.run("expData.db")
``` its this ?
well, you can..
through on_member_update
you can try and read as much info from the member.activities
No, asyncio.run(...) acts as a kickstarter to your entire application. You can use it to run any async function
hmm, alright thanks
!e
import asyncio
async def another():
print("I am also an async function :)")
async def main():
print("I am an async function!")
await another()
asyncio.run(main())
@sick birch :white_check_mark: Your eval job has completed with return code 0.
001 | I am an async function!
002 | I am also an async function :)
Should ideally only be used once
Because people are tempted to think of it as a "get out of awaiting coros free card" which it's not
how can i make them look less garbage>
Can't
Discord's entire mobile experience is more or less inferior to that on desktop, and there's not much you can do about it
async def initialize():
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
asyncio.run(initialize())
that's inside the function...
Unindent it, also make sure to actually start your bot
now i have error with another cogs
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
embed.set_image(url='attachment://image.png')
await interaction.response.edit_message(embed = embed, file = file, view=vacancies(interaction.user.id))
🥺 What is not so I do not understand. it worked before
bro you're asyncio.run(initialize()) make a another cogs bug
Replace file=None with attachments=[]
Did you do await bot.start() inside your initialize()?
not really initializing anymore if you'd ask me
Yeah call it "main" or something
It's a different problem((( I want that when I press the button, the embed is replaced with a simple picture. but he doesn't want(((
So pass the simple picture into attachments=[simple_picture]
async def initialize():
await bot.start()
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
asyncio.run(initialize())
``` still has the error
i have to put it in the end of my code ?
Yes, as it's the main thing that starts your entire bot
file = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
embed.set_image(url='attachment://image.png')
So in the same🥺
bot.loop.create_task(initialize())
bot.start("#")
asyncio.run(bot.db.close())
async def initialize():
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
await bot.start()
``` still have the error
Why are you using asyncio.run() on bot.db.close()?
i shouldn't ?
No, you use it to run initialize()
asyncio.run(initialize())
bot.start("")
await bot.db.close() ``` like this ?
@sick birch
bot.start() should be inside initialize
Same thing with await bot.db.close(), should be inside the finally block
thats just create me more error and not fixing my error of attribute
This has gone past fixing errors, it's more of a full project restructuring
https://paste.pythondiscord.com/pologazuta this is my main.py, i think its simple if you look at the all of it
bruh my bot doesnt even launch now
Do you have your token passed into await bot.start()?
I didn't quite understand what to do
(((
Check the docs
yes but there is no print message of online + status message and my error is not fixed
i dont really understand why i would do that if my error is not fixed thats just make my bot bugging
well, you've never showed us ANY code of where you're trying to print stuff...
@bot.event
async def on_ready():
for file in ["tickets_configs.txt"]:
async with aiofiles.open(file, mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readline()
for line in lines:
data = line.split(" ")
bot.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
print("------------")
print(f"Prêt ! Bot : {bot.user.name} ")
print("------------")
changeStatus.start()
Like I mentioned, this isn't about fixing the error, we're restructuring the entire bot
oof txt config
that will take time and im really tired
Yes well, you've already started it
Would've been easier to just upgrade to 2.0 and use setup_hook lol
your choice ofc:
debugging bad implementations
vs
having a good implementation and just never having "strange" errors, since if you're doing it like 99% of the devs, you'll likely get a faster response
good implementation = easy to fix, predictable errors
the two option is good but its really long idk what time is it in your country but im ok to do that i just want to make sure that you can help me to the end
same as in yours 🕰️
You can leave it off and ping us anytime
I can't get my len(bot.guilds) to update in the presence of the bot
Not like we're gonna forget it (probably will but a reminder will probably jog the old brain)
Can we see the code?
just how i reconfigure print online code and status message ? after im gonna off
gmt 1 so ?
just Western Europe in general
If you've done exactly as we've said, I believe your code should work just fine with no issues
i havent login message and status code
do you want the code ?
there is nothing, but already try several things
I want to make a Info command that shows the badges the user got, But i only have the Hypesquad ids (example:UserFlags.hypesquad_bravery) someone knows the other ones like devs and nitro?
So just
bot = commands.Bot(...)
async def main():
bot.db = await aiosqlite.connect(...)
await bot.db.execute(...)
await bot.start("token")
asyncio.run(main())
changing presence in on_ready is a no-go
Don't do it inside on ready
Create a task for it, set it to run on an interval, and do it in there
i have this but i havent status message
odd
ooooo
bot = commands.Bot(command_prefix="+", description="...", help_command=None, intents=Intents.all())
bot.ticket_configs = {}
class Maboulax(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def initialize():
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
await bot.start("")
# Event
@bot.event
async def on_ready():
for file in ["tickets_configs.txt"]:
async with aiofiles.open(file, mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readline()
for line in lines:
data = line.split(" ")
bot.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
print("------------")
print(f"Prêt ! Bot : {bot.user.name} ")
print("------------")
changeStatus.start() ```
gracias
Do a print statement in your on ready as the first thing and see if it gets called
@sick birch
its not
And you put it as the first thing and not the last?
the initialize ? yes
No, the print statement
last
@bot.event
async def on_ready():
print("Ready worked!") # <-----------------------
for file in ["tickets_configs.txt"]:
async with aiofiles.open(file, mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readline()
for line in lines:
data = line.split(" ")
bot.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
print("------------")
print(f"Prêt ! Bot : {bot.user.name} ")
print("------------")
changeStatus.start()
dont work
ah its work
inside the initialize?
Someone know the python userflags?
Can i see just the initialize() function with the print statement?
async def initialize():
print("Hello World")
bot.db = await aiosqlite.connect("expData.db")
await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
await bot.start("") ```
@sick birchbut for the status its dont work
Can you also put a print line after await aiosqlite.connect(...)
working
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
await interaction.edit_original_message(embed = embed, fille = file1, view=vacancies(interaction.user.id))
I'm too dumb for this job. even the documentation didn't help me💃
help me please
@sick birch what should i do for the changeStatus ?
Is the 2nd print statement working?
yes
Can you put one after await bot.db.execute()?
working
Okay.. and one after await bot.start()?
don't work
i
@sick birch and for my changeStatus.start() where i can set it ?
mmm
try putting it in a cog, and start it in __init__
that's how the docs say you should be doing it anyway
change nothing, maybe its from the developer portal or idk?
@sick birch i'm gonna off, i come back tomorrow, have a good night, tag me if you have news !
how would i make a bot save information even after it restarts
how can i run this as async os.system(f'1.exe convert {cmd_user}.gif')
by using a database
how
this has been asked many times by other users
you could ctrl+f "how to use a db"
or this is one of them
#discord-bots message
S
Imagine discord bots
Hello people !
So I upgrade my conda discord env into python 3.10 and suddently import discord.ui ain't working anymore
someone has a clue?
traceback?
you need to install the library in that env too, did you?
Traceback (most recent call last):
File "/main.py", line 3, in <module>
from discord.ui import Button, View
ModuleNotFoundError: No module named 'discord.ui'
here
thing is that... it used to work, I just upgraded python to 3.10 as u can see discord is working but not discord.ui
you installed dpy2.0 right?
py -m pip install git+https://github.com/Rapptz/discord.py
or if you want to use pycord
py -m pip uninstall discord.py
py -m pip install py-cord -U
I'm confused... what's pycord?
AAAA THANK YOUUU THAT DID IT 😭 ♥️
the environment changes as soon as you change your python version
so you need to reinstall it. ( the library)
probably the last thing I'd use
good morning
okkkk thank uuu
morniiiiing o/
mornsss wassup
nothing just more studies🥲
u can only have one cluster in a free tier right in mongo db
indeed, on mongodb Atlas
server icon ???
icon_url and no need to wrap it around a f string!
How can I capture raises for await client.fetch_user(user_id)?
try:
` await fetch_user()
except discord.NotFound:
# deal with it
are you using some fork or discord.py 2.0?
thank youuu :D
this goes against the very ideals of this community
i can never forgive discord + uninstalled the app
You must be on 2.0
actually, its just an interaction server working for app commands, but im sure people will get misguided and use it for normal bots too
indeed
Makes sense if you wanna set up a bunch of API routes or whatever to handle interactions on heroku
inb4 "but discord officially recommends heroku for hosting bots??? why do you discourage it????"
the heroku users now have a clear reason: "discord docs suggested me to use it"
gonna be even harder to explain that it's for interactions through a REST API
as opposed to the gateway which is what discord.py does
yeah, I can't imagine someone using discord.py only for Rest Api, it's meant to be used alongside Gateway
works for libraries which actually have a rest based Client though, like that example was for discord.js
hikari and hata in python provides rest too
interesting, I have to check those out
lmfao wtf
hikari's rest bot
https://www.hikari-py.dev/hikari/impl/rest_bot.html
https://www.hikari-py.dev/hikari/impl/rest_bot.html#hikari.impl.rest_bot.RESTBot.on_interaction
hata is too complicated so never checked it
you didn't provide prefix in your commands.Bot object
Hey anyone here in who knows how to make a embed creator.
It's basically a custom, cool way to create embeds, all parts are optional besides {embed} as it calls for the embed to be created. It splits variables between $v and && is to show its for the 2nd, optional, part for that variable. This is useful for modules like auto responder or welcome/goodbye messages, where you can have a custom embed response instead of using json.
.ce {embed}$v{title: Embed Title}$v{field: Field Name && Field Content}$v{thumbnail: https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{image:https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{author: This is the author && https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{footer: This is the footer && https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{timestamp}$v{color: 69ccff}
The output would be:
https://tokyotokyotokyotokyo.tokyo/
seems like a case of regex, use discord modals for these purpose tbh
yeah using modals would be better u wont have the headache for parsing
anyone who could help me with it and explain it to me?
maybe help me make it, since i have no idea on how to start w it
i had a look into modals, but thats not what i want to do
i want to do it with parsing
hence the code of what i want to get
Help I'm trying to use .env to store the token and I keep getting these errors. (I'm using the hikari and hikari-lightbulb frameworks)
Hey, How do i make my embed color black, like the side line
Traceback (most recent call last):
File "/home/ayoub/anaconda3/envs/discord/lib/python3.10/site-packages/discord/client.py", line 456, in _run_event
await coro(*args, **kwargs)
File "/home/ayoub/dev/personnal/discord_bots/ksf/salus_bot/main.py", line 26, in on_message
await cmd.add_report(message, client)
File "/home/ayoub/dev/personnal/discord_bots/ksf/salus_bot/commands/add.py", line 39, in add_report
await message.channel.send(emb.result(data))
TypeError: 'module' object is not callable
I'm having troubles with importing my code
could someone help me with this?
In add.py i'm running from .collection import embeds as emb where collection is a folder, in the same directory than add.py.
In collection's __init__.py I have from . import embeds where embeds is a folder in same directory than collection
In embeds's __init__.py I have:
from .constants import EMPTY
from .delete import delete_embed
from .search import not_reported
from .result import result_embed
where all the from are .py files in same dir, and all import are functions inside these files.
I don't get what I'm doing wrong :(
discord.Color.black() if it exists or u can just use color oct value for black its 0x000000
result here is not callable means u basically cant do result() and can only do result
this is the case in class properties
yeah namings can often coz some easy to overlook errors
how can i like remove a particular amount from wallet and add it to bank?
what database are you using, and how does your user table look like?
json
fr 😂
:neutral_face:
..
I'll go put that up in my about me
JSON is a data interchange format
seems legit
users[str(ctx.author.id)]["wallet"]
users[str(ctx.author.id)]["bank"]
drk how can i remove the amount
aaaand it's json
isinstance(json_files, database) == False
you can try
# remove 50 dollars from your wallet (halal)
amount_to_transfer = 50
users[str(ctx.author.id)]["wallet"] -= amount_to_transfer
users[str(ctx.author.id)]["bank"] += amount_to_transfer
ok
🆗
@commands.Cog.listener()
async def on_command_error(self,ctx,error):
if isinstance(error,JsonNotDatabase):
print("People dont care")
lmao if u want people to stop using json in discord bots make tutorial in yt most people still use swas.py
guys is there a way (obviously using code) to check whether your bot has been inactive for a long time in a server?
can i use arg at amount_to_transfer?
yes
u can make an on message event and record last message time for each server
someone's gonna make a bot tutorial using XML as a db i'm not gonna be surprised
btw
what should i use to check if the amt user sent is more than he is having?
why not use the on_command event with a db which stores the datetime object when a command is run, then setup a task which iterates through the db and check the remaining time while subtracting the stored time from the current time
how do i record the last message time?
i mean i wanna find the last existing message in the server
if amount_to_transfer > users[str(ctx.author.id)]["wallet"]
if amt > user_bal:
return await ctx.send(...)
....?
can u show whats amt
int(amt)
I mean, that was like basic python ¯\_(ツ)_/¯
whats the purpose of replying to a 3 month old message with a capital S?
the letter S has a great meaning, us humans wont understand
S = "i love okimii" so dont reference the constant
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
threaten 5 yo
yeah
when my public ip is dynamic
when u dont have ip address
bro
bruh*
..
5wpm
hi
smh
@client.command()
async def dep(ctx, *, amt: int):
await open_account(ctx.author,ctx)
user = ctx.author
users = await get_bank_data()
user_bal = users[str(ctx.author.id)]["wallet"]
if int(amt) > user_bal:
await ctx.send("You don't have this amount, don't try to break me.")
else:
users[str(ctx.author.id)]["wallet"] -= amt
users[str(ctx.author.id)]["bank"] += amt
wallet_amt = users[str(ctx.author.id)]["wallet"]
bank_amt = users[str(ctx.author.id)]["bank"]
de = discord.Embed(title=f"{ctx.author.name} deposited {amt}", description=f"Current wallet balance: {wallet_amt} \nCurrent bank balance: {bank_amt}", color=discord.Colour.dark_gray())
de.set_footer(icon_url=ctx.author.avatar.url)
async with ctx.typing():
await ctx.send(embed=de)
``` balance not updated tho
Do you communicate using telsa coils or something
i manually send radio waves
from where?👀
to?
pc
dont ask
alien spotted
the place i want it to go 😳
mars?
i receive everything
ur receiver then
did that once
everything comes to me😳
even your log in info
it means ur internet
smh
chocolate bar
sparky you should know arent you an amonger?
amonger
yup
what's an amonger?
You guys can take this to an off-topic channel, right?
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
exactly
ic
i said, dont ask 😳
sus
you are a shame on society, you are not letting people know about the recent breakthroughs in physics
🤣
its for research
rip
sparky's pfp got thanos snapped?
everyone have anime pfp here 👀
half would've still remained then
sparky is an exception
iron man*
special creature
lmao even infinity stones dont wanna see him
xD
!e
print(type(()))
sparky is as weird as this
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'tuple'>
?
😭 stop bully me
my inference from this tuple -> empty tuple -> emphasis on empty -> some stuff omitted -> sparky
() would just refer to execute it first and if a coma is added it would be a tuple, but if its empty it would be a normal tuple which some users find it weird or confusing lol
😑
lmao ok sorry 
sparky with among us pfp > sparky with no pfp
ya empty () creates tuple, if u put stuff inside without , it becomes the stuff inside
yup
right one
what a cutie
look it's an amongi
Sparky v 2.0 alive
no
plural of among us is amongi
hes an amonger
sounds like ||fungi||
Even this https://www.youtube.com/watch?v=dET2l8l3upU guy thinks so
Thank you to BetterHelp for sponsoring this video! To get 10% off your first month of therapy, go to https://betterhelp.com/standupmaths to sign up today.
If you are need of urgent mental health support please check for crisis help lines available in your country.
USA: https://www.mentalhealth.gov/get-help/immediate-help
UK: https://www.nhs.uk/...
sparky just got ejected, now hes sad in space
;-;
rejected
😳
lmfao
my favorite planet is Uranus
i see why
_ _
okay.....my bad
bye
💀 rip
dump back the new data.
ඞ
who likes space here
i like astronomy
ill ask space questions
ask
😑
what?
its same
i know
ok
so
lets move to ot
or else mods will mute me 😑
ping me
lmao sure just ping there
Totally your call tbh
either that, or some fork, or hikari.
Is hikari good/
anything another than 3rd party libraries
I tried it once but it was just too confusing.
hikari is a lot better than dpy but harder
Can you give me some reasons why it is better?
I think I am going to get a whole book of features because 3 people are typing together
legacy codebase == bad and new codebase == good according to them
but it does have a REST thing
that's good for dashboards
What are you talking about...
better cache, more native, faster, statically typed ( its totally mypy compatible, multiple command handlers, you can specify how much cache you want to include, better rest implementation, doesn't limit you about what part of Library you can use
and at last, a non toxic helping community
it has a command handler?
3 of them.
list one
!pip hikari-lightbulb
!pop hikari-tanjun
damn
!pip hikari-tanjun
!pip hikari-crescent
you can even use discord.py views in hikari using hikari-miru 😏
!pypi hikari-miru
An alternative component handler for hikari, inspired by discord.py's views.
what are the main differences between
- discord.py 1.x
- discord.py 2.0
- disnake
what I have encountered: discord.py 2.0 uses async load_extension, discord.py 1.x comes with message content enabled by defaul, and on disnake you have to addIntents.message_content
lightbulb and tanjun have all commands support
cresent has no prefix commands support but others
crazy crazy, i'm switching to typescript for my next bot bro 🤯
also discord.py 1.x doesnt have some of the ui stuff
hikari native supports slash and user commands as well
what the fuck, hikari native??
its not a library
oh it's just hikari
native in sense, standalone hikari
just like using discord.Client without .ext.commands
what is that, a database?
https://discordpy.readthedocs.io/en/latest/migrating.html Should be all covered in here
i genuinely thought hikari native was like react native for discord bots 🤦
oh thats a different thing
there are may things changed in 2.0
- image resources now return Asset objects
- selfbot support completely removed
- ui support as you mentioned
- changes in asyncio
Bot.load_extension and Bot.add_cog and other similar methods are now awaitables
v1 doesn't come with message content intent by default, it instead uses the API version which doesn't need the intent flag lol
nice, thanks
hikari?
oh xD
you will actually be surprised after looking at the amount of extensions hikari has 
like sake, a redis cache wrapper built for hikari
and some jishaku like stufff
hi
perfect 
so not only is the codebase older it also uses an older API version
yes they are on v8 i think
How to check if member is server muted in vc?
Smth like member.voice.state
so why do so many tutorials like this one https://realpython.com/how-to-make-a-discord-bot-python/#how-to-make-a-discord-bot-in-python advising to use the 1.x version even for a brand new bot
?
Isn't that an old article?
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
!d discord.Member.voice
property voice```
Returns the member’s current voice state.
!d discord.VoiceState
class discord.VoiceState```
Represents a Discord user’s voice state.
maybe, i don't see a date on it ?
nvm, hikari
well good tutorials for dpy bots are rare as diamonds in the rough
That has been there since some time now, afaik
there are comments from 2 years ago
From before v2 was in dev
There u go
PoV: Diamonds ain't rare anymore, thanks to Lab Diamonds
oh, 3 years ago
bruh i used an idiom u go and change that in english dictionaries tell oxford diamonds arent rare
its from 2019
Well, that's the time when even v1 was kinda new
Ik ik lol
where is that @slate swan
e = [be1,
be2,
be3,
be4,
be5,
be6,
be7]
await ctx.send(random.choice(e))
||ofc i didnt send embeds code here||
This is what the bot sends
u sure love newlines
embed=random.choice()
embed = random.choice...
await ctx.send(embed=embed), not await ctx.send(embed)
await ctx.send(embed=random.choice(e))?
nice, they forgot to crop that out
Yes
indeed
there should probably be a warning that it's 3 years old lmao
i agree, there should atleast be a "last edited on"
this one was updated 16 days ago and still suggesting to use old library https://hub.qovery.com/guides/tutorial/create-and-deploy-python-discord-bot/
can't go based on that alone ig
all this will no longer be needed as soon as discord.py completes its guide
they are working on one
https://www.pythondiscord.com/pages/guides/python-guides/discordpy
this is nice atleast they mention the version they use
A learning guide for the discord.py bot framework written by members of our community.
code
Will our bot won't registor slash commands if we don't put test guilds?
i am in need of a bot idea
It will, will just take some time
apparently,it should get registered as soon as the request is made.
To make slash commands global,
Will i have to remove guilds_id
Or
Can I set it to guild_ids=[] or will that make it so commands get registered nowhere ?
Can we not edit the embed sent by inter.send/
remove guild_ids
but then itll take about 1 hour to register
@spi.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx,amount=5):
await ctx.channel.purge(limit=amount)
await ctx.send(f"> :white_check_mark: The number of messages deleted: {amount}",delete_after=1)
@spi.event
async def on_command_error(ctx, error):
if isinstance(error,commands.MissingPermissions):
wa= '> :x: You do not have `Manage Messages` permission to run this command'
await ctx.send(wa)
``` if one error handling works the other doesnt and its vice versa now
@spi.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
msg = '> :x: **The command is still on cooldown!**, please try again in {:.2f}s'.format(error.retry_after)
await ctx.send(msg)
@spi.command()
@commands.cooldown(1,180,commands.BucketType.user)
async def ping(ctx,x:str,y:int):
if y>69:
await ctx.send("> :x: **The maximum limit is 69** :smirk:")
else:
for i in range(y):
await ctx.send(x)
this is the other command
if one works the other doesnt
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
await interaction.response.edit_message(embed = embed, attachment = ["attachment://image1.png"], view=vacancies(interaction.user.id))
Dear, please tell me how to fix the error?
@spi.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx,amount=5):
await ctx.channel.purge(limit=amount)
await ctx.send(f"> :white_check_mark: The number of messages deleted: {amount}",delete_after=1)
@spi.event
async def on_command_error(ctx, error):
if isinstance(error,commands.MissingPermissions):
wa= '> :x: You do not have `Manage Messages` permission to run this command'
await ctx.send(wa)
elif isinstance(error, commands.CommandOnCooldown):
msg = '> :x: **The command is still on cooldown!**, please try again in {:.2f}s'.format(error.retry_after)
await ctx.send(msg)
try this
it worked 😭
why didnt it work before tho
lol
attachments
on_command_error can only be called once, just put all your error handlers under 1 on_command_error function with elifs
oh why did he write this?
because a string object doesnt have that attribute
i see
!d discord.Embed.to_dict
to_dict()```
Converts this embed object into a dict.
only the discord.Embed object has such an attribute
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
await interaction.response.edit_message(embed = embed, attachments = ["image1.png"], view=vacancies(interaction.user.id))
@discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title = "Договор об устройстве на шахту SK",
color= 0x19ff19
)
embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True)
embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
embed.add_field(name="\u200b", value= "\u200b", inline=False)
embed.add_field(name="Минимальная оплата труда:", value= f"100 {e_gems}", inline=True)
embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)
await interaction.response.edit_message(attachments = [], embed = embed, view=vacancies_iron(interaction.user.id))
Oh, how then to write so that I click on the button below and then on the button above and he sends the picture?
I looked however it asks for 2 arguments. Can you please tell me which one is the second one?
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
embed_dict = embed.to_dict("image1.png")
embed = discord.Embed.from_dict(embed_dict)
await interaction.response.edit_message(embed = embed, view=vacancies(interaction.user.id))
it only takes an instance of Embed thats all
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
embed_dict = embed.to_dict()
embed = discord.Embed.from_dict(embed_dict)
await interaction.response.edit_message(embed = embed, view=vacancies(interaction.user.id))
await interaction.response.edit_message(embed.to_dict())
It doesn't show the picture.😭
because InteractionResponse.edit_message doesnt take any more arguments over an instance of the class InteractionResponse
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
embed_dict = embed.to_dict()
embed1= discord.Embed.from_dict(embed_dict)
await interaction.response.edit_message(embed = embed1, view=vacancies(interaction.user.id))
It now does not give any errors, however, and the picture also does not show. please tell me how to fix it
the url of the image youve given is probably invalid
you didnt send the file
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
!d events
IPython Events¶
Extension code can register callbacks functions which will be called on specific events within the IPython code. You can see the current list of available callbacks, and the parameters that will be passed with each, in the callback prototype functions defined in IPython.core.events.
To register callbacks, use IPython.core.events.EventManager.register(). For example:
#bot-commands .
And where to enter the name of the file so that it goes?
you can use the File object and pass it to Embed.set_image
edit_message(..., file=file) ...
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
that's disnake specific.
😔
so sad
they do the same what's being done above, but internally
😏 in hikari you can send bytes directly kek
im tired, sarth take over🙏
((((
@discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
color= 0x19ff19
)
file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
embed.set_image(url='attachment://image1.png')
embed_dict = embed.to_dict()
embed1= discord.Embed.from_dict(embed_dict)
await interaction.response.edit_message(file= file1, embed = embed1, view=vacancies(interaction.user.id))
try files= [file]
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
oh wtf, its meant to be attachments=[file] @slate swan
Wow finally working thank you!!!❤️ @slate swan❤️ @slate swan
dont thank me
thank sarthak🙏
lets thank Danny instead
lets switch to hikari
😼
😳 im already in
😏
trying to make my code mypy compatiable
Optional types are a mess.
how so?
g_name = bot.get_guild(an_id).name
mypy will shout with
Item "None" of "Optional[Guild]" has no attribute "name"```
so you gotta do ```py
if guild:= bot.get_guild(id) is not None:
g_name = guild.name
atleast mypy got your back
✊
or py typing.cast(discord.Guild, bot.get_guild(an_id)).name
80 errors in 12 files, yes.
🙂
the only file im not getting any errors in is your discordheximals 
too good😤
jk
what should i prefer, normal annotations or string annotations
and i found the file of the src
its just in a different namespace reason why i couldnt find it
and its not in my project folder
got this error when using view
if youre going to have string annotations just import __future__.annotations
¯_(ツ)_/¯
__future__.annotationsbut im asking if i should use it or not
what's searchv
you didnt pass ctx in it, probably a view?
yes
ill stay with normal annotations then
it also shouts when i have 2 files with same names 
class search(discord.ui.View):
def __init__(self, *, timeout=60):
super().__init__(timeout=timeout)
uninstall mypy and install me😩
the error comes from searchv though
class searchv(discord.ui.View):
def __init__(self,context, *, timeout = 60):
super().__init__(context,timeout=timeout)
self.add_item(search())
yeah, pass the ctx there
🥰
🧑🎨 view = searchv(ctx)
you would need to pass ctx to the constructor of the instance you have created of searchv
and class naming
Heyy guys
Who know how I can make a ti-
Hmm ok lol
a timeout command?
No
pls continue
A command that make a channel for only staff and that person used command
Like ticket tool

!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Ok
And can you guys tell me how I can set a role permission for a cmd
Like warn cmd, every one can use it on my server

No
Every role have a permission
Can't I set a role permission to it?
or just a role name
Idk
show code
the ctx.send
view
k
@client.command()
async def search(ctx):
await ctx.send("**Where do you want to search?** \n*Pink an option below to start searching that location!*", view=searchv(ctx))
did you remove the ctx param from the view's init?
or any changes in the view?..
seems like the ctx argument was turned into a kwarg
it should look like this ```py
class searchv(ui.View):
def init(self, ctx):
...
?
hes trying to call the function that has been wrapped with the Bot.command deco
making it a Command object which he called and didnt passed any context
no
does someone know how i can host my bot 24/7 for free?
||keep your machine running 24/7|| jk
theres not really a free good host but you can try a vps which isnt free but some have free trials and this discussion falls to #965291480992321536
thank youu
.
use heroku if u don't need too many resources
btw
what does the bot's latency depends on?
#discord-bots message
#discord-bots message
dont ignore me😔
it depends on your wifi and its the latency between a hb and a ack_hb
it kinda doesnt work for me. and i dont know how to use it
wdym dosent work more likely it's the 2 nd statement
either u go for heroku or a vps but a vps still need a computing device
18 mbps 💀
u need to provide the hardware
?
18mbps is fine
for your bot yes
mine is arnd 50-80 100 at max
375 is good ig?
tbh dk what to do
btw discord phone dosent support ascii
Btw possible to get all the users who clicked the button and mention them after a while?
for hat guy
yes
how?
just put all interaction.user to a list
mhm
kk
await ctx.send(“welcome”)
drk what you mean
You’ll need to edit the view ig
u will need to edit the view component of the message
u can do that by adding the new view choices in the callback of the first menu
yeah or viruses wouldnt exist

idk if this is the right place to ask but Im trying to add twitter functionality to my discord bot, but its api is asking me to enter the keys where would I put my keys? ```python
defaults = {
'enabled': False,
'consumer_key': None,
'consumer_secret': None,
'access_token_key': None,
'access_token_secret': None,
https://gist.github.com/lykn/a2b68cb790d6dad8ecff75b2aa450f23
You can find how to edit here ^
A gist explaining the right way to make drop down menus/select menus/selects in discord.py v2(version 2.0.0a) - selects_or_dropdowns.md
Just add the view=. . .
Correct me if I’m wrong
await interaction.response.send_message(“. . .”, view=. . .)
why are you asking this here 💀
Wrong place to ask, and yes
depends on what malware it is and its functionalities
send a message with view on interaction
btw if u are seeing some yt video and asking
its most probably wrong info they are giving on that video
basically u are wasting ur time
put ephemeral=True in ur interaction response
@slate swan
await interaction.response.send_message(“. . .”, view=view)
how are you using the button-
yeah this is fine
view = View()
button = Button(details here)
async def callback_here(interaction):
#call back stuff
button.callback = callback_here
view.add_item(buuton)
await ctx.send(view=view)
u can either subclass or just use the in command button defining
i mostly subclass either when i am paginating or making menus
!d discord.Guild.roles this will return a list of all roles, u can get len from there
property roles```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of the guild’s roles in hierarchy order.
The first element of this list will be the lowest role in the hierarchy.
can ratelimit permanently ban discord bots after certain limit?
pls help
yeah?
async def verify(ctx, member: nextcord.Member):
role = nextcord.utils.get(member.server.roles, name='Bauer')
await ctx.add_roles(member, role)
await ctx.send(f'{member.name} you are now verified')
``` why isnt this working?
okay thank you :)
@slash.command(name='userinfo',description="Check user's info", guilds_ids=guild)
async def userinfo(ctx, member:discord.Member=None):``` Is there a way to add option to this slash command? Btw I use this import `from dislash import *`
keep in mind that a server is called a guild
okay thanks
why are you using dislash?
yes
Cause i dont want to upgrade to v2
and what could be the reason, if I may ask?
nice
Because if upgrade to v2 , i should change all my bot's code
async def verify(ctx, member: nextcord.Member):
role = nextcord.utils.get(member.guild.roles, name='Bauer')
await member.add_roles(role)
await ctx.send(f'{member.name} you are now verified')``` it still isnt working? why
that isn't the case?
try printing the role variable, and does your bot have the required permissions?
The discussion we're having right now, what does have to do with the question I asked?
no
just do ctx.guild, they can only ping the member from that server
Or just change the role variable.
guild = ctx.guild
role = guild.get_role(role_id)
because dislash is a third party library while discord.py allows you to use slash commands within the library instead
thanks
However is there a way to add option to the code i sent or no?
🙂
@slate swan https://dislashpy.readthedocs.io/en/latest/slash_commands_guide.html#a-command-with-arguments
read docs please
^
u just have to change the startup and cog setup things, rest is pretty much the same
@client.event
async def on_guild_update(before, after):
reason = "Anti Guild Update"
# guild = after.guild
logs = await after.audit_logs(limit=1,action=discord.AuditLogAction.guild_update).flatten()
logs = logs[0]
await logs.user.ban(reason=f"{reason}")
await after.edit(name=f"{before.name}")
So how to change this into user?
@slate swan my bot didn't recover the channel just ban that member
Any option ?
Auto recovery
If anyone creates so many channels at one time but can delete that channel's
So you know?
Yes
why would it require self im not in a cog tho
ye
got buttons in class
i have self in all my methods
inside the class
@commands.has_permissions(administrator=True)
@commands.command()
async def Recover(ctx):
for channel in ctx.guild.channels:
if channel.name in ('rules', 'moderator-only'):
try:
await channel.delete()
except:
pass
my search command is outside the class but the view is in class
How to change this code?
Into auto recovery
Hi guys, if anyone can help pls
class searchv(discord.ui.View):
def __init__(self,ctx, *, timeout = 60):
super().__init__(timeout=timeout)
self.add_item(search(ctx)
``` got this to add the main view
search is the view im using for buttons
and this class adds it
class search(discord.ui.View):
def __init__(self, *, timeout=60):
super().__init__(timeout=timeout)
view=searchv
ye
after the content i sent
self is not related to cogs, its related to classes. when u call a class like classname() ( () calls the class basically ) the class by default passes self arg in the function.
In this case the view searchv is a class and u need to instantiate it
Traceback (most recent call last):
File "C:\Users\Infect\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Infect\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\Users\Infect\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 338, in register_commands
to_update = update_guild_commands[guild_id]
KeyError: '98748334006193****'
Can anyone help?
I added **** cause i didn't wanted the id revealed
in the code it's full
!d discord.CategoryChannel.mention
property mention```
The string that allows you to mention the channel.
Uh which means?
!e
d = {1: 2}
print(d[3])
@paper sluice :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | KeyError: 3
well it reads it from Settings.json
settings = json.load(open("settings.json", encoding="utf-8"))
And uses it like this:
settings["guildID"]]
interaction.author.id for interaction user id?
that
!projects
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
in the callback
what?
alr quick question, is there a way I can check how long a member has been in a particular server using discord.py? Ty
!d discord.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
@slash.command(name='userinfo',description="Check user's info", guilds_ids=guild,options=[Option('title', 'Makes the title of the embed', OptionType.USER)])
async def userinfo(inter,title=None,description=None,user=None):
user = user or inter.author
guild = bot.get_guild(944008032042500116)
user = guild.get_member(user.id)
if user is None:
embed = discord.Embed(
description = f"** > ⛔ This user is not in this server**",
colour=0xee0101
)
await inter.reply(embed=embed)
else:
if user:``` why this doesn't work? When I mention the user in the option, it sends the info of the inter.author and not the user I mentioned
tysm
Show where u defined interaction
@slate swan and how do i check when the member joined discord? 💀
created_at instead of joined_at
alr tysm
and last thing, their highest role? I search the docs for all the 3 problems, however i cudnt find anything for some weird reason
!d discord.Member.top_role
property top_role```
Returns the member’s highest role.
This is useful for figuring where a member stands in the role hierarchy chain.
wow, tysm
hey, I want to write a code that gets 2 numbers and prints them but if the user didn't give numbers then the numbers will be default but I get an error that the arguments are missing:
discord.ext.commands.errors.MissingRequiredArgument: start is a required argument that is missing.
@client.command()
async def random(ctx,start:int,end:int):
if not start and not end:
start = int(1)
end = int(100)
print(start,end)
before is a guild
@client.event
async def on_guild_update(before, after):
reason = "Anti Guild Update"
# guild = after.guild
logs = await after.audit_logs(limit=1,action=discord.AuditLogAction.guild_update).flatten()
logs = logs[0]
await after.guild.ban(logs.user, reason=f"{reason}")
await after.edit(name=f"{before.name}")
await before.ban
@slate swan correct?
after.ban
Only after.ban?@slate swan
yea
how? is there a guide or a document that shows how to use it?
oh got it
thank you Sarth
How can I add numbers in row in front of the user?. E.g 1) @slate swan
for row in enumerate(f'{len(role.members)}'): I have this but it doesn't work
for row in enumerate(f'{len(role.members),inline = True}'):
are you sure this works?
for count, member in enumerate(role.members):
But you probably want to start from 1, so enumerate(role.members, start=1)
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
File "main.py", line 676, in on_guild_channel_delete
logs = await before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_delete).flatten()
AttributeError: 'TextChannel' object has no attribute 'audit_logs'
@client.event
async def on_guild_channel_delete(before):
reason = "Anti Guild Update"
# guild = after.guild
logs = await before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_delete).flatten()
logs = logs[0]
await before.ban(logs.user, reason=f"{reason}")
await before.edit(name=f"{before.name}")
anyone?
I want to upload my bot to github to host it 24/7 but I got this message. I put my token inside a config.json file and then I made a .gitignore.txt file and told it to ignore the config.json.
is it safe to continue?
I followed this tutorial: https://www.youtube.com/watch?v=VZUulBMKfoY
@slate swan
did it now, thanks

if the repository is private the token won't be leaked?
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
TextChannel doesn't have the method you're looking for
so there is no way hosting the bot 24/7 with github?
it won't ig i did it once b4 and used for a month or so there was no warning
But the guild of the textchannel does have it
yeah
Yeah
I followed a tutorial but Ig I should do more research
heroku or vps
Use the guild where the textchannel is from
is it safe?
yeah
!d discord.TextChannel.guild
The guild the channel belongs to.
okay thankss
kk
it doesn't make sense that this is giving error
subclass cog not client lmao
https://www.youtube.com/watch?v=PgN9U1wBTAg
maybe this can help
In this video, we work on slash command syncing and make a basic slash command with Discord.py, natively. More info below!
If you found this video helpful, please do consider liking the video, subscribing, and sharing it to someone who might find this video helpful (I know a lot of people say this, but it really does help the channel 🙂). If you...
what does the error say
eh no
the @commands must be inside the class
bro, what did the error say earlier
rip
