#discord-bots
1 messages · Page 1055 of 1
you would make a subclass of the View class above the cog subclass so it would be define or just use an instance of it
I want to learn how to do something like that!!!
let me give you an example
Did I did this nicely?
@bot.command()
async def gban(ctx, user: disnake.User):
for guild in bot.guilds:
await guild.ban(user)```
Or I messed up smth?
I will be only glad and grateful
do you just want the ban command?
No, I own like a network of server so I want to be able to ban person from all servers
by one command. I guess thats the right way
class Confirm(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
# When the confirm button is pressed, set the inner value to `True` and
# stop the View from listening to more input.
# We also send the user an ephemeral message that we're confirming their choice.
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Confirming', ephemeral=True)
self.value = True
self.stop()
# This one is similar to the confirmation button except sets the inner value to `False`
@discord.ui.button(label='Cancel', style=discord.ButtonStyle.grey)
async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Cancelling', ephemeral=True)
self.value = False
self.stop()
class MyCog(discord.ext.commands.Cog):
def __init__(self, bot):
self.bot = bot
# your command
@commands.command()
async def MyCommand(self, ctx):
# creating an instance of your view
MyView = Confirm()
# sending a message with the instance of your View subclass
await ctx.send("Message", view=MyView)
the most basic command i can give
seems good to me but youll get ratelimited
thank you very much!!!!!!!
❤️
Can someone check this?
# GLOBAN BAN SYSTEM ------------------------------------------------------------------
@client.command(description="Globally bans user from all LARPC related servers.")
@command.has_permissions(administrator=True)
async def gban(ctx, user: disnake.User=None, *, reason=None):
try:
if (user == ctx.message.author or user == None):
await ctx.send("You cannot globally ban yourself / that person!")
return
if (reason == None):
await ctx.channel.send("You have to specify a reason!")
for guild in client.guilds:
guild.ban(user, reason=reason)
print(user)
print(guild)
print(reason)
await ctx.channel.send(f"{user} is **succesfully GLOBALLY banned** for {reason}!")
channel = client.get_channel(801446246954827808)
await channel.send(f"{user} has been **GLOBALLY banned** by {ctx.author} for **{reason}**!")
except:
await ctx.send(f"Error 404: I cannot GLOBAL ban {user}!")```
It's supposed to ban a person from all server he shares with bot.
it can be done better in many ways
uhm
@slate swan
@discord.ui.button(style= discord.ButtonStyle.grey, emoji= "✅")
async def button1_callback(self, button, interaction, ctx, * , member: discord.Member = None):
await interaction.response.send_message(f'**{ctx.author.mention}** занялся сексом с **{member.mention}**')
self.value = True
self.stop()
@discord.ui.button(style= discord.ButtonStyle.grey, emoji= "❌")
async def button2_callback(self, button, interaction, member: discord.Member = None):
await interaction.response.send_message(f'{member.mention}, вам отказал')
self.value = False
self.stop()```
I don't understand why he doesn't like this ctx!?
```Ignoring exception in view <MyView timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label=None emoji=<PartialEmoji animated=False name='✅' id=None> row
=None>:
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
TypeError: button1_callback() missing 1 required positional argument: 'ctx'
- you should follow pep8
- no need for the () in the first if statement
- why the bare except, you should only have them in rare occasions
4.you can just return a message object without returning anything to save a line - again no need for the () in the second if statement and you should compare entities with
is - discord.Guild.ban is a coroutine
- you would easily get ratelimited
- Context already has a .send coroutine so no need to get a TextChannel instance
- i would check if the channel is in cache with
Bot.get_channe()land if not i would useawait Bot.fetch_channel()
async def button2_callback(self, button, interaction, ctx, member: discord.Member = None): @brave forge ?
oh it's in 1
UHHHHHHHH
could you help me 
well button callbacks dont need context or a member object they only need the interaction argument and the button argument thats all, so if you want a member object you would need to pass the object to an instance of the class in a command
with?
what ?
please ignore my message
@dull terrace and it is better to blacklist them altogether so as not to see them
means discord_channel object has no attribute send
https://paste.pythondiscord.com/ayomamuwed , someone help me please
Ok
that command uh
okay this is a simple button
@discord.ui.button(style= discord.ButtonStyle.grey, emoji= "✅")
async def button1_callback(self, button, interaction):
await interaction.response.send_message("You pressed me!")
in all buttons it only takes the button argument which would be satisfied by a Button object and a interaction argument which would be satisfied by an Interaction object so Context would not be passed nor can it, so you would need to pass the context of the command which sends the view to your views subclass init
can someone help with my code
dont ask for help, just show ur code and error
well im not gonna give you all together as i gave you all the problems and its better to do it yourself as you learn more!
that u can do, thats literally basic python
basic python as said
Now this one
btw nice twitter api wrapper
u didnt fetch the textchannel object
that is, in these buttons it is not as impossible to put what they should do the link of participants !?!?
well its kinda trash and doesnt work but i have another api wrapper which is currently being maintained which is in my about me if you would like to check it out!
i did check it out lol
yeah you can! you can pass it to the subclass initiate!
thanks!
OMG
Who developed discord.py ?
i tried , the code then gives me more errors
How I want to see his hands under a sledgehammer
if someone can help me out that would be great
I have a ban there
😅
They just couldn't fight back any other way
how can i tell if my bot is reciving DMs instead of server messages? i want to give my bot special commands that can only be activated through DMs, but the problem is my bot cant tell if its responding to an DM or not (which also causes attribute errors, but i know how to solve those)
@client.event
async def on_message(message):
if message is a DM:
# do special stuff
else:
# do normal stuff
well you can check if the guild is None or you can check the channel type
!d discord.Message.guild
The guild that the message belongs to, if applicable.
thx
!d discord.ChannelType.private
A private text channel. Also called a direct message.
Did you import requests
you would need to import the module and you should use aiohttp
so it wont block your bot
import requests
youre confusing it with the async sqlite driver aiosqlite!
please tell me what gives this " self.value = None" ??
well, in the example its used to defer and check which button was pressed
should remove request
!d aiohttp.request
async-with aiohttp.request(method, url, *, params=None, data=None, json=None, headers=None, cookies=None, auth=None, allow_redirects=True, max_redirects=10, encoding='utf-8', ...)```
Asynchronous context manager for performing an asynchronous HTTP
request. Returns a [`ClientResponse`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientResponse "aiohttp.ClientResponse") response object.
and you could use this!
Hi can anybody tell me how is the guy who reacts to a message defined in code
well you should be using the request function which the aiohttp module has
all the people who reacted to the message?
yeah like someobody send a message so we use message.author or ctx.author so like that for reaction
well is it an event for reactions or on message?
for reactions
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member
and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only...
maybe is that what youre looking for? i kinda need more context
!D indentation
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
@bot.event
async def on_member_join(member):
if member.guild == bot.get_guild(960516503613079582):
emoji = '✅'
guild = bot.get_guild(960516503613079582)
member = member
Channel = bot.get_channel(960516503613079584)
message = await bot.get_channel(960516503613079584).send(f"{member.mention} has joined the class")
await message.add_reaction(emoji)
@bot.event
async def on_reaction_add(reaction, member):
guild = bot.get_guild(960516503613079582)
Channel = bot.get_channel(960516503613079584)
if reaction.message.channel.id != Channel.id:
return
elif reaction.emoji == "✅":
if member.id == 724460131110354984:
Role = discord.utils.get(guild.roles,id=int(961235844704919562))
await member.add_roles(Role)
This is my code
so umm if you could help with this it would be great
ah well yes you would check the users with this async iterator and since its a async iterator of user object you could just use the id attribute the User class has
The user’s unique ID.
alright tysm 🙂
Can someone please help me...
anytime❤️
well its a basic indentation error which is kinda basic python you should read about them here https://www.geeksforgeeks.org/indentation-in-python/ or here
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
i have thx
doesnt work i tried indenting and i still get the error
may i see the error?
show your code
can i send in a hastebin?
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
😅
remove line 16
well your problem is with your context managers i assume as their indentations are quite off
ok
also, don't do shit in on_ready
yeah you should make a task or overwrite setup_hook
done
idk i have a bunch of the code i just dk what to do at this point
you've just copy pasted stuff without actually doing it correctly
let me guess, you came from sqlite and tried to make everything async via aiosqlite
this seems like an XY problem
ok well context managers always expect expressions as so
async with ...:
# pass an expresion
the only time you actually need the cursor, is when you're fetching stuff, so you're actually SELECTING something
all the insert and UPDATE bullshit doesn't even need a cursor in aiosqlite
import discord
from datetime import datetime
TOKEN = "Token"
client = discord.Client()
@client.event
async def on_ready():
print("RUNNING")
LOG_CHANNEL_ID = 977285171738976296
def generate_embed_description(message: discord.Message) -> str:
# timestamp = datetime.now().strftime("%d/%m/%Y, %H:%M:%S %p")
timestamp = message.created_at.strftime("%d/%m/%Y, %H:%M:%S %p")
url = message.jump_url
return (
":writing_hand: `Author:`\n"
+ message.author.mention
+ "\n\n :robot: `Channel:`\n"
+ message.channel.mention
+ "\n\n"
+ ":speech_balloon: `Message:` \n "
+ message.content.split("\n")[0]
+ "\n\n :watch:`Send at:`"
+ "\n **"
+ timestamp
+ "**"
+ f"\n [Jump to message]({url})"
)
@client.event
async def on_message(message: discord.Message):
if (
message.channel.category.id != 977285171738976296
or message.author.bot
or message.content == "-clear"
):
return
embed = embed_for_user(message.author)
if "\n" in message.content:
embed.add_field(
name=message.content.split("\n")[0],
value="".join(message.content.split("\n")[1:]),
)
else:
embed.description = generate_embed_description(message)
embed.color = 0xDD4C59
file = None
if message.attachments:
file = await message.attachments[0].to_file()
file.filename = file.filename.replace("_", "")
embed.set_image(url=f"attachment://{file.filename}")
channel = client.get_channel(LOG_CHANNEL_ID)
await channel.send(embed=embed, file=file)
if message.channel.id == LOG_CHANNEL_ID:
await message.delete()
def embed_for_user(user):
embed = discord.Embed()
embed.set_author(name=f"{client.user.name}", icon_url= client.user.avatar_url)
return embed
client.run(TOKEN)
print(client.user.name)
where is the error its not running
what shall i do then lol can u copy my code and edit it lmao
if you revert the changes back to when it was sync ( I hope you still have them )
you'll maybe understand it better
doesn't matter, do it
so all executions are async with client.db.execute("")?
you only need
# when selecting
async with client.db.execute(<here is a select query>) as cursor:
result = await cursor.fetch()
# when inserting or updating or whatever
await client.db.execute(<here an update or delete or whatever>)
await client.db.commit()```
I really hope you see WHY
im so confused lol
so what should i remove from my code ?
just ask line per line
"I had this single thing, how do I make that async?"
since all select queries etc should just be handled the same etc
@bot.event
async def on_member_join(member):
if member.guild == bot.get_guild(960516503613079582):
emoji = '✅'
guild = bot.get_guild(960516503613079582)
member = member
Channel = bot.get_channel(960516503613079584)
message = await bot.get_channel(960516503613079584).send(f"{member.mention} has joined the class ! Bhak bsdk pehle May I come in ma'am bol")
await message.add_reaction(emoji)
@bot.event
async def on_reaction_add(reaction, user: discord.User):
guild = bot.get_guild(960516503613079582)
Channel = bot.get_channel(960516503613079584)
if reaction.message.channel.id != Channel.id:
return
elif reaction.emoji == "✅":
Role = discord.utils.get(guild.roles,id=int(961235844704919562))
await user.add_roles(Role)
Hi , just revised my code but still doesn't work . Can anybody help
do the events ever get invoked?
how to import "ctx, * , member: discord.Member = None" via initiate in class.
yes
alright, so what are the errors/ what do you expect to happen?
im trying to create a system which gives a member a role when someone reacts but the user is not getting the role
no errors on the console tho
lets start off slow py @client.event async def on_ready(): print('Bot has loaded') setattr(client, "db", await aiosqlite.connect("level.db")) await asyncio.sleep(3) async with aiosqlite.connect(client.db.cursor) as cursor: async with client.db.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)") as cursor:
is this fine? one by one
alright, so waht does the on_member_join have to do with this?
no, as told earlier, don't do shit in on_ready
then wtf do i do...
its cuz when a new member joins
you make a startup task which does this for you
ever made a task?
no
great
read some documentation about it, there are simple examples
so your task should just do what's in the on_ready
(this task will run as soon as the bot is online)
first lets look at the full code then focus on tasks
the entire code?
yeah, idk
ok sure
And then I see the problem of "A man who doesn't understand that if I knew how to solve it, I wouldn't write here."
it will mean alot
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
kk
if it is not related to Disocrd.py . Then don't be offended, but I will start insulting and humiliating you
go ahead
btw you can also use !xy its handy!
with pleasure, but there are too many rats who will immediately call the moderator
the complete file, there's lots to rewrite probably
including all my ban commands and everything?
just the whole stinky file
can we stop insulting each other?
ok lmao\
and people who follow rules arent called "rats" there called people with respect and sense so please stop.
entire code , i only didnt add token
hey
hi hi!
oki you got any ideas about the v2 perms, i mean can bots edit it anyways?
wdym v2 perms
I have already come across the fact that when I insulted me mute. And when they didn't have anything for me
@potent spear what i sent , is that fine?
pls guys lets keep it civilize and lets respect eachother!
integration permissions, like the slash command perms
editing as we speak
okey
not sure if theres even endpoints for them
i havent checked
mm lemme recheck the docs
I need the run method too, just without the token
kk
are they wrapped tho?
btw may i ask how long you'll be , i have plans tonight so i might be busy thats why im curious
i havent seen any new endpoints in the Guild class
30 secs, but I'm waiting for you to include the run method in the code...
wdym
you removed the line
same, thats why i asked
I have to wrap functions around that line
its client.run("token id")
even in hikari, its just a pr rn
wasnt that released like 2 months ago or something like that how is it still a pr?
I know that
I want the whole code again with that line included
ok lmao
🚶♂️ they review and rewrite it like 3 times
To me this seems like an application command equivalent to channel overwrites, it seems to work almost exactly the same as well. That being said it’s probably safe to assume that bots may edit them
😭
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
the endpoints seems similar
🚶♂️ https://github.com/hikari-py/hikari/pull/1148 its been there for more than a month
21 days actually*
😵💫
It doesn’t make sense to not allow bots to edit their slash commands permissions as well. Considering the fact the bot account actually registers the command, etc
Otherwise that would be kind of a huge design flaw
well yeah that makes sense
and from the pr i see they are allowing to edit the permissions so ig that works
the file exists in the ssame project file, im using cogs btw
inside the cogs folder?
no
it should be?
i've tried the code before without it being inside the cog folder and it worked fine
upto you, show your file structure
a minute
thats it
ok
I gotchu
from pathlib import Path
json_file_path = Path(__file__).parent.parent / "config.json"```
you should know what to do with this
@potent spear any updates?
pathe = Path(__file__).parent.parent / "config.json"
config = json.load(open(pathe))
prefix = config.get('Command Prefix')
```, code just stops and does nothing
with open(pathe) as f:
config = json.load(f)
prefix = config.get("Command Prefix")
line 3-8?
thats just a copy paste mistake
yeah
lol, idk how that got there
😅
still just runs and dies
a simple debug will do
WHERE you place those lines also matters
I partly fucked up, , tasks on line 10 and whole line 22 (the task decorator) don't have to be there
@potent spear
under py if __name__ == '__main__': asyncio.run(main()) do i just do client.run(token) ?
that line is already above that if statement
wdym
line 223
Oh I see
Btw is that Save
New
Duplicate & Edit
Just
Text
Twitter
Is this important
nope, that's a typo
Will my system work then ?
Also did u change anything apart from the db shit or just that
ofc, just remove those lines
yup, some small changes, you'll notice maybe if you'd scroll through 🧠
you're looking for tasks
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html?highlight=tasks
thanks i couldnt remember the name to save my life
Any changes to my commands ?
Cuz I cba lmao
just a rewrite, not like actual breaking shit
Ok
like
if member == None:
member = ctx.author```
changed to
```py
member = member or ctx.author```
also your hardcoded
```py
# Do the command prefix which is > , ....
changed to
f"Do the command prefix which is {client.command_prefix} , ...```
xd I’ll fix that
I already did that...
omg thx , may i ask why did u help me so much xd
because you were slightly annoying me with the same question for days
just now look what I changed, so you can UNDERSTAND
ok]
there's no task in your code...
hi everyone! I want to make a dice game and I need the bot to send a message with consent and reaction, the person who was offered to play should click on the reaction and only after that the game will start. Please help me!
this is a task, which you don't have
what's your knowlegde of this library or python in general?
yup
File "C:\Users\Dom\Desktop\cluckz\main.py", line 215, in main
client.loop.run_until_complete(setup_db())
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 617, in run_until_complete
self._check_running()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 579, in _check_running
raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running```
xd
bad start
so what shall i do
i try to do via on_raw_reaction_add but nothing works. I do not understand how to assign the id of the newly created message
change the run_until_complete to create_task
what you're actually looking for is wait_for check that out in the docs
wtf
@potent spear do i have to put these at the top of my cog for the task loop
self.index = 0
self.printer.start()
ty
you're copy pasting code, do you know what this does?
never used task loop its a new concept to me
well, read what it is first
Traceback (most recent call last):
File "C:\Users\Dom\Desktop\cluckz\main.py", line 220, in <module>
asyncio.run(main())
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "C:\Users\Dom\Desktop\cluckz\main.py", line 216, in main
client.run("token")
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 719, in run
_cleanup_loop(loop)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 90, in _cleanup_loop
_cancel_tasks(loop)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 75, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 617, in run_until_complete
self._check_running()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 579, in _check_running
raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running```
xd
@potent spear
current code?
@warped mirage how well do you know py
@potent spear
so i remove , tasks and @wild nestks.loop , just these 2 lines?
@wild nestks
did I say otherwise?
yes?
nope
exactly as said
, tasks , tasks .loop dont have to be there
yup
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 713, in run
loop.run_forever()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\windows_events.py", line 321, in run_forever
super().run_forever()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 585, in run_forever
self._check_running()
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 579, in _check_running
raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Dom\Desktop\cluckz\main.py", line 219, in <module>
asyncio.run(main())
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 641, in run_until_complete
return future.result()
File "C:\Users\Dom\Desktop\cluckz\main.py", line 215, in main
client.run(token)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 719, in run
_cleanup_loop(loop)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 90, in _cleanup_loop
_cancel_tasks(loop)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 75, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return
RuntimeError: Cannot run the event loop while another loop is running``` i cant show all but this is the most
I'll try a small rewrite
@warped mirage why dont you sort your code into cogs so its easier to use and more organized
i can but i need help xd
are you using just py in the code
yes
how long ago did you start
i used to be good but i recently came back to coding , i know how to make a cog file but i need help adding the stuff into it , considering i need to fix my level system
ill help you with cogs if you help me learn embeds
check dms
@hasty chasm lets chat here its fine
when i start bot , it auto goes back to py PS C:\Users\Dom\Desktop\cluckz>
your json file is empty
@warped mirage any error?
is the bot online?
has it ever been online
yes bruh
have you always used vs code
because you need an enviroment file to get it online
there's no error or anything, I can't...
same issue
your code doesnt have the word token anywhere is it in another file?
i have 1 file bruh
if the if statement isn't True, it'll never run
you cant host the bot because theres no token or env file so idk how you ever got it to go online
then how do i fix it lmao....
make an environment file
used_json is still empty
you need an env file its required for vs
like the code wont listen unless you make an evn file and throw the token in there
No?
I never used env bruh
I always use client.run
you know what your right im sorry
maybe just remove if __name__ == '__main__':
I did.
and..?
Bro I copied what u sent me
I noticed you have a task without a cooldown
can u add a cooldown to it and see what happens?
well, the if statement was in there...
class Buttons:
def __init__(participants):
self.participants = participants
particip = ...
buttons = Button(partip)```
strange
FINALLY
just isnt
hmm, well you could google that error optionally
coolcool
what's the code that prints this?
done
sounds like complete bullshit
@potent spear the code that u gave me breaks all my commands , non respond
the level system blocking them or smth
You have an on_message, right?
how do I import a mention of participants into a class using initiate?
"import a mention" what?
Add
await client.process_commands(message) on the last line of that event
That’ll do
class MyView(discord.ui.View):
def __init__(self):
super().__init__()
self.value = None
@discord.ui.button(style= discord.ButtonStyle.grey, emoji= "✅")
async def button1_callback(self, button, interaction):
await interaction.response.send_message(f'**{ctx.author.mention}** занялся сексом с **{member.mention}**', initiate = True)
self.value = True
self.stop()
@discord.ui.button(style= discord.ButtonStyle.grey, emoji= "❌")
async def button2_callback(self, button, interaction):
await interaction.response.send_message(f'{member.mention}, вам отказал', initiate = True)
self.value = False
self.stop()```
To make this work ({ctx.author.mention}, {member.mention})
I'm not quite understanding
@sick birch class does not see these mentions
Nah doesn’t do anything
I’ll just try again tommorrow
@sick birch how to mention the author and the mentioned participant ?
Make sure it’s not in any if statement ofc
interaction.user.mention
So it must be await on like the start basically
It can’t line up with other awaits in the event . Got it
thank you very much
@sick birch
ERROR
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\ToxicPenguin\Desktop\disocrd bot python\cogs\fun.py", line 16, in button1_callback
await interaction.response.send_message(f'**{interaction.user}** занялся сексом с **{interaction.user.mention}**', initiate = True)
TypeError: send_message() got an unexpected keyword argument 'initiate'```
Remove initiate=True
thank you very much
@sick birch i need some help
What's the issue?
so my pip is broken, I can't update it I tried a few cmds in terminal. and in command prompt none worked.
You'd have better luck asking in #python-discussion or opening a help channel to recieve one on one support (see #❓|how-to-get-help)
ok
Works lol but now my lvl command and that doesn’t work
xD so many problems
Just do command per command, I’m out
What do you need async and await for?
like what do these commands do?
They signify to Python that "hey, this task might take a while, so go do something else while you wait for this to happen"
Usually you use them for I/O tasks (databases, network requests, files, etc) as these all take some time (relative to how fast python is)
!d discord message.delete
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
@sick birch can you give me the right docs for when a message is deleted in a channel how do you recover it and post the image else where?
Do you mean message logging?
yes but unknown.png is shown not just the name
of it
!d discord.on_message_delete
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the
internal message cache, then this event will not be called.
Messages might not be in cache if the message is too old
or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") parameter
or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
alright,
but whats the difference between them too then?
Difference between async and await?
yes
Async defines a coroutine, which is basically a function that says "hey, this is not a regular function because if you call it, you won't get a return right away. it'll take some time"
Async functions are coroutines, which are a way to represent something that happens in the future
I like the name Javascript gives them: promises
It's a promise that something will happen later, just not right now
And you can await these async functions like so:
async def this_function_takes_a_long_time():
# do something that takes a long time
await this_function_takes_a_long_time() # python will do something else here
await ctx.send("Hello")
Exactly. That's a network request which means it can take a while
but it doesn't
Not to you
just the ping time
To the computer? It takes a really long time
depends on speeds
really
30ms, for example, to a computer is a really long time because they can do a lot in those 30ms
So instead of sitting around and doing nothing while you send a request, you can just go and do something else
@client.event
async def on_guild_join(guild):
try:
link = await random.choice(guild.text_channels).create_invite()
except:
link = "I don't have perms to create an invite"
channel = await client.fetch_channel(the channel id)
await channel.send(f"Server Name - {guild.name} ({guild.id})\nServer Member Count - {len(guild.members)}\nServer Owner - {guild.owner}\nServer Invite - {link}")
It says invalid sytax
@tasks.loop(seconds=3)
async def DN_cycle():
TH = bot.get_channel(977319265822711888)
day = 0
await TH.send('it is day' + str(day))
day += 1
@DN_cycle.before_loop
async def before_DN_CYCLE(self):
message = await self.bot.get_channel(977319265822711888).fetch_message(977301094524923955)
if message.content == 'True':
return
await asyncio.sleep(3)
how do i get the loop to actally start
i have self.DN_cycle.start() under my cog and im getting no errors
where?
in the init function
class Cog(commands.Cog):
def __init__(self):
self.bot = bot
self.DN_cycle.start()```
what's the purpose of the before loop anyway?
once a day send a message saying a day has passed in game
its at 3 seconds now for testing purposes
yeah i get that but
message would never equal 1
did you mean to get the content of the message?
let me edit it i changed it
yeah the message content
thats what it is now
the message changes so and i only want it to work when the message is true
which is why i have the if check in the before loop
have you tried printing at any point just to debug?
it prints the message content
every 3 seconds?
no it doesnt print anything with the loop
command is telling the bot to do something
event is waiting for something to happen like a person joining the server or the bot coming online
@slate swan
Thanks
@slate swan i found out it stops at the line of the message fetch
How to len admins in the ctx guild?
check each member in the server see if they have the role then count += 1 each time and then print the count
By permission*
what
You were talking about the role
how can i get avatal_url for a footer from a specific id
not the author
idk if you can check the perms youll have to wait for someone else to answer @lyric apex
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets
all the traits passed in `attrs`. This is an alternative for
[`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using
logical AND, not logical OR. Meaning they have to meet every
attribute passed in and not one of them...
Ohk
I used member for member .... And it worked
if arg1 == 'eng':
if role2 in member.roles:
emb = discord.Embed(description = f'{member.mention} **вже прийнятий та має потрібні ролі** \n {member.mention} **already accepted and has the necessary roles**', color = 0x6d41a8)
await ctx.send(embed = emb)
#########################
if roleforum or rolecur in author.roles:
if ctx.channel.id == 975549648557207582:```
i need it to break after the place where # the code is
but idk where use break
thanks to your message i didnt have to ask my question thanks
I really don't know where to write it. no matter where I write it, it throws an error:
when my discord bot receives argument for command, it interprets the star emoji as ⭐ instead of :star: which is messing up the code
should i just replace the strings with the actual emote instead of :star: or is there some way to convert the emote to the name?
ok it actually looks cleaner in code to use ⭐ so im gonna do that
Where are you writing it?
in the if block, before it, and tried many options. where should i write it for the code to work?
Well the error says it. It needs to be inside of a loop, be that a for loop, a while loop
Though I'm not seeing why you want it
I need the code to break after
if role2 in member.roles:```
return
why didn't it work...
Can you explain what your code is trying to do? I don't fully understand
And knowing what it does could help me figure out what's wrong and find out if there's a better way
i can send all command code today after 13 PM. i wanna sleep...
dm or this chat?
Possible to run a command without giving all the arguments?
Open up a help channel
Sure, make them optional
how?
!e
def function(optional=None):
print("I am an optional function!")
function("Hello, world!")
function()
@sick birch :white_check_mark: Your eval job has completed with return code 0.
001 | I am an optional function!
002 | I am an optional function!
Same syntax, works with commands with no arguments
@bot.command()
async def optional_command(ctx: commands.Context, optional_argument=None):
...
can u show code
argument = None
so I want to automatically create a webhook that will send a message to a channel, i have this code right here ```py
@client.event
async def on_message(message):
if message.content == 'create':
await message.channel.create_webhook(name = 'hook')
await message.channel.create_webhook.send("What's up")
but it doesnt do anything
does it create the webhook?
error:
@client.command()
async def trade(ctx, item, price, item2, price2, item3, price3, optional=None):
await ctx.channel.purge(limit=1)
tradeE = discord.Embed(title="{ctx.author.name} is waiting for a trade!", description="{ctx.author.mention} Is trading {item} for {price} \n {item2} - {price2} \n {item3} - {price3} \n \nAny Trade Scam Done Via This Trade Command Will Not Be Tolerated.",
color = discord.Colour.magenta())
tradeE.set_footer(text="Click The Button Below If You Want To Trade")
await ctx.send(embed=tradeE, view=view23)
code ^
can u send a screenshot
of code
How can I implement a "only you can see this message"
ephemeral=True
after the content you sent
Ok thank you
Can I use it with embeds?
yes, the content can be an embed but do remember that ephemeral messages can only be sent within interactions
@slate swan ^
view = view23()
adding onto this, you may also use typing.Optional to make it Optional though doing it as =None is the easiest way to make an arg Optional
why would you use a class over just setting its value?
Hey how can i make it so that my bot only reacts to images. so far i made a bot that reacts to specific people whenever they type but now i want to make it so it reacts only to images in a channel
how do i make my reaction bot only react to images?
you can check if message.attachments meaning the message has attachments with it. and then attachment.content_type to check whether it's an image (PNG/JPG)
!d discord.Message.attachments
A list of attachments given to a message.
!d discord.Attachment.content_type
The attachment’s media type
New in version 1.7.
Did it
But it says trade command not found
I have this command in another file
Would the if message.attachments work here?
async def on_message(message):
if message.channel.id == 929345014205653014 and \
if message.attachments
await react(message)```
Nvm I’ll add it in my mainfile
if its in another file you gotta use cogs....
could you please send your code here in a codeblock isnteaed of as screenshots
!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.
yes i will
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = '//')
@bot.event
async def on_ready():
print ("I have awoken")
async def react(message):
custom_emojis = [
":okay:"
]
guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
for emoji in custom_emojis:
#print(emoji, guild_emoji_names)
#print(emoji in guild_emoji_names)
if emoji in guild_emoji_names:
await message.add_reaction(emoji)
@bot.event
async def on_message(message):
if message.channel.id == 929345014205653014: and \
if message.attachment:
await react(message)
you're using this function to just get one emoji and react to the message with it?
async def react(message):
custom_emojis = [
":okay:"
]
guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
for emoji in custom_emojis:
#print(emoji, guild_emoji_names)
#print(emoji in guild_emoji_names)
if emoji in guild_emoji_names:
await message.add_reaction(emoji)
comparing ids sounds like a better option
why not just do guild.get_emoji or whatever
yea, the :okay; is the emoji
the default emoji?
okay is not a default emoji
no its a custom one from my server
whenever i launch it, it just closes
@client.command()
async def trade(ctx, item, price, item2, price2, item3, price3, optional=None):
await ctx.channel.purge(limit=1)
tradeE = discord.Embed(title="{ctx.author.name} is waiting for a trade!", description="{ctx.author.mention} Is trading {item} for {price} \n {item2} - {price2} \n {item3} - {price3} \n \nAny Trade Scam Done Via This Trade Command Will Not Be Tolerated.",
color = discord.Colour.random())
tradeE.set_footer(text="Click The Button Below If You Want To Trade")
button = Button(label = "Trade", style = '3', emoji=':Pepe_Business:')
async def button_callback(interaction):
await interaction.response.send_message(f"Hey {ctx.author.mention} **{interaction.user.mention} has accepted your trade!")
button.callback = button_callback
view = View()
view.add_item(button)
await ctx.send(embed=tradeE, view=view)
command isnt working
my msg gets deleted but the embed isnt sent i have no on_message events
anyone know why this code for my bot that reacts to images is not working?
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = '//')
@bot.event
async def on_ready():
print ("I have awoken")
async def react(message):
custom_emojis = [
":okay:"
]
guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
for emoji in custom_emojis:
#print(emoji, guild_emoji_names)
#print(emoji in guild_emoji_names)
if emoji in guild_emoji_names:
await message.add_reaction(emoji)
@bot.event
async def on_message(message):
if message.channel.id == 929345014205653014: and \
if message.attachment:
await react(message)
hello... i'm opening pool with aiomysql.create_pool in discord.py v2.0a setup_hook ... where should i put cleanup code? pool.close()?
How do I make status to put in the bot?
!d discord.on_disconnect most probably
discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed.
This could happen either through the internet being disconnected, explicit calls to close,
or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_connect "discord.on_connect") call.
"This function can be called many times" ... 😦
yea, every time your bot "disconnects" from the API
which is quite rare
you can use on_connect to create the pool again..
PoV: The internet goes out every other day
what exception is connected with this error and where i can find knowledege about this because i couldn't find this in python docs(specifically api reference):
Converting to "int" failed for parameter "amount"
^^^
Haha ik ik
the command needs an integer argument, you provided something else
i know this but i need exception name and that is what i couldn't find
!d discord.ext.commands.BadArgument
exception discord.ext.commands.BadArgument(message=None, *args)```
Exception raised when a parsing or conversion failure is encountered
on an argument to pass into a command.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError "discord.ext.commands.UserInputError")
thanks
anyone know if its possible for my bot to pickup commands executed by other bots? (like to let other bots use commands of my bot)
yea sure
override your on_message and just add this await bot.process_commands(message)
tf does that mean? im not making the commands in the on message
im using @bot.command() etc etc
you can either read the docs and understand it yourself, or try to understand what other tell instead of "tf"ing it
yeah but you want other bots to use the commands, so just do what sarth said, the commands are gonna work as intended, you'll have to override the default on_message in order
ah mhk ic
kk leme fix em
commands dont work magically, they use on_message event which i just asked to "override"
and you got a "tf"
😔 ikr
better yet use listen
"override"
Hi can anyobdy tell mw the code to remove all reactions from a message
!d discord.Message.clear_reactions
await clear_reactions()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes all the reactions from the message.
You need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.
async def callback(self, button, interaction):
button.disabled = True
then edit the view
what's the endpoint to get guild information on discord? using raw api and not a third party lib
Anyone help me at making a image search command pls
Me not getting good tutorial on Google
guys i need help
!pip icrawler
you would have to make your own asynchronous downloader though
@slate swan yo indents are fixed lol
dunno
at last
sure
!paste u can use this
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
ye i use it
good
anyone know why this code for my bot that reacts to images is not working?
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
bot = commands.Bot(command_prefix = '//')
@bot.event
async def on_ready():
print ("I have awoken")
async def react(message):
custom_emojis = [
":okay:"
]
guild_emoji_names = [str(guild_emoji) for guild_emoji in message.guild.emojis]
for emoji in custom_emojis:
#print(emoji, guild_emoji_names)
#print(emoji in guild_emoji_names)
if emoji in guild_emoji_names:
await message.add_reaction(emoji)
@bot.event
async def on_message(message):
if message.channel.id == 929345014205653014: and \
if message.attachment:
await react(message)
:okay: isn't in guild emojis?
hi, how do I connect a bot without any libraries?
Is it possible to keep the built in help (cmd name) cmd and remove the default help cmd which shows all the cmds
wym, i followed a tutorial and expanded on it, what is a guild emoji
@client.event
async def on_member_join(member):
channel = client.get_channel(969946795780223056)
embed = discord.Embed(title=f"Welcome {member}", color=discord.Colour.blue())
await channel.send(embed=embed)```
Why does this code not run?
What's the error?
you're contradicting yourself....
get_channel is returning None or members intent isnt enabled
you may like to fix that using a getch
channel = client.get_channel(id) or await client.fetch_channel(id)
Intents?
The event was working a bit but not for every user and command doesn’t work at all
no🥲
why does this code not run?
@client.event
async def on_member_join(member):
channel = client.get_channel(969946795780223056)
embed = discord.Embed(title=f"Welcome {member}", color=discord.Colour.blue())
await channel.send(embed=embed)
This if block should have an else statement for those who have xo and level in the db
show your intents
How?
show the line where you do client = commands.Bot
It just checks that level or xp is present if it isn't then the code goes on else it just jump to process command
or intents = discord.Intents.default()
and everything that's related
So how can I fix this
@client.event
async def on_member_join(members):
channel = client.get_channel(977464331589545994)
intents = discord.Intents.default()
embed = discord.Embed(title=f"Welcome {members}", color=discord.Colour.blue())
await channel.send(embed=embed)```
Thus?
Just add an else statement for the condition that level and xp is not None
please help🥲
show your code 😫
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Idk how xd
I’m just so confused atm
if not xp or not level:
#add user to dB
else:
#add xp to user
What do I add in the else and if
I made this, what should I do now?
I made this, what should I do now?
if not xp or not level:
async with client.db.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,)) as cursor:
await client.db.commit()
else:
try:
xp = xp[0]
level = level[0]
except TypeError:
xp = 0
level = 0
#rest of the code
Wait after . The rest of the code is my entire code remaining ye
The command should work
Rest should be in the else statement, except for the process command
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
class CONFIG:
TOKEN = ""
PREFIX = "^"
intents = intents
client = commands.Bot(command_prefix=CONFIG.PREFIX)
client.remove_command("help")
@client.event
async def on_member_join(members):
channel = client.get_channel(977464331589545994)
embed = discord.Embed(title=f"Welcome {members}", color=discord.Colour.blue())
await channel.send(embed=embed)
client.run(CONFIG.TOKEN)```
THIS IS MY CODE
Apart from what u gave me do I change anything else
What I gave you should fix the event I haven't read the levels command tho
Add intents Param to commands.Bot as shown above
Like this
will this do?
wdym
I mean show the whole code
Like in a hastebin?
No a screenshot will do
Kk wait
Wait I have a problem
It does this idk I need to fix something
Yea I forgot about that
Ok
So what shall I fix lol
This bit should be inside the if statement
Hmm ok
Ya
What's the error now?
why?
Just try
I have the answer in my head but dunno how to put it to words
ok so level.db gets deleted?
Try the event and see if it gets added in the db
nah doesnt work
If I take them out of the if statement it works but it’s broken
tbh, your implementation of levelling seems messy ngl
https://github.com/Dark-Light007/Darker/blob/main/db/experience.py this is actually my implementation of levelling, I prefer making helper functions and using those rather than writing sql straight to the code
you could take a look though "maybe"
I do the same thing
can yall help me add a rank card to it?
does it work?
first fix the stuff..
most probably will, havent tested them yet, but most of the code was copied from a library I made for databases
and it worked fine
what database do u use?
sqlite
no-
I just told you to refer not copy 😭
xD
plus its a whole lot different
smh
anyone down to help or not 👀
bro..... thats just opposite of what they need, they want their bot to respond to other bots :/
bruh
what even is the error?
idk
can someone here helpp
wdym
i am stuck with second code of my bot
like we can use 2 different codes for same bot on different machine right ?
Anyone know how to make a tiktok notification bot?
tiktok's api allow that ?
Yes there’s other bots
wdym by two different codes ? u can load cogs with different codes in the bot
yt tutorials u can ask if u have any doubts
if u want a good tutorial i can recommend u to one
very simple for beginners
its like i don't have enough resources on 1 system
so i am trying to run separate codes on different machines
but with same bot id
why ?
discord doesn't take code to its database and respond accordingly
it sends events to machine which is running code
it's same as can u have 2accs to the same userid
and discord allow multiple logins with same token
No yt tutorials
hmm intresting
No google results
Idk what I can do?
not commands
what are ur events?
on_message
u have process_commands on that right?
i don't have it in first code
await bot.process_commands(message)
message 🙃 why ?
and its commands work without processing commands
on_message(message)
its working fine
on message will intercept the command
but @commands.command() not working
u need a process command to make it work
np i learned something new too
but don't you think its pain because on_message is passsed with messageable and commands are passed with context
its better to use a listener than an event, a listener does not override the default on_message event and works perfectly fine without a process_commands
it need changes like ctx.send to ctx.channel.send
yeah but on message event always occurs before the command acts so if u add a return in on message ur commands will fail
yeah that's fine too
cool didn't know that, thanks!
only applicable for a message command*
yes ma'am
smh
😂
is there any way i can get the channel id from a message? something like
channel_id = message.channel.get_id()
channel.id ig
thanks
trying to start discord task but I get zis error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'coroutine' object has no attribute 'start'
well
show code.
5 sec
I did
@tasks.loop(seconds=10)
async def testloopyuwu(joe):
if joe:
print('joe')
@client.command()
async def joemama(ctx):
testloopyuwu(True)
uh
🚶♂️ tasks, dont take args like this
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with
optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
what loop
!d discord.ext.tasks.Loop.start
start(*args, **kwargs)```
Starts the internal task in the event loop.
you cant pass args in a task
call this
testloopyuwu.start(True)
wait, how 2 run a task multiple times?
I want them to be like threads
running constantly untill users wants them stopped
How would i add this? Does anyone know the documentation if any
then either get the event loop and run them
cool thanks
wdym? could yo gimme some docs or examples
im trying to use the 'random' api, can someone tell me how to take the output and print a different reply depending on what the randomized output is? thought it might be as simple as an if command but idk how to apply it
could you elaborate
like reply w/ a completley random string?
idk how to paste as code but this is what i got sec
if message.content.upper() == "A":
random.choice(LOOTED_CHEST_RANDOMIZER)
if [1, 2]:
message.channel.send("slip and fall")
using an item list on the randomizer
im experimenting atm to see what works
Does anyone have a slight clue on whenever I run my bot, it tells me to enable intents, so I do but then it just breaks my bot entirely and throws no errors
but should that do it?
random.randint(1,2)
the list is 1 thru to 6
if 1 then slip and fall else
you want the random number to be generated from 1 - list size
im still new to py, can u explain what u mean
You mentioned that the list is 1 - 6, what are you trying to do?
im trying to create several chance outputs, only got the 1 in there so far. ie, 1 or 2 causes x, 3 or 4 causes y, etc
number = 1
if number == 1:
print("The number is 1")
elif number == 2:
print("The number is 2")
else:
print("The number is unknown")
want a total of 4 diff outputs depending on the 'dice roll'
how do i apply that to the current tho? would i still be drawing from a list?
Can you send me your script?
ie could i put that below the current part
I just started learning python, can you help, complains about line 232 https://pastebin.com/4SySak12
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
remove "=" from that line
also, your bot token leaked, you're gonna need to regenerate it
this is an obsolete token
ok
removed = but did not help
it should be os.getenv("TOKEN")
did not help
you also need to set environment variable "TOKEN" to your token... or use a different metod to load token value
with variable order, complains about syntax
AttributeError
'NoneType' object has no attribute 'strip'
Can anyone help me how to use @unkempt canyon is our bot pls
Me dont know how to use dockerfile
i need help
petpet gif isnt working on linux
May 21 14:01:40 Lab1 bash[2497]: await func.invoke(ctx, **args)
May 21 14:01:40 Lab1 bash[2497]: File "/home/pi/.local/lib/python3.9/site-packages/discord_slash/model.py", line 210, in invoke
May 21 14:01:40 Lab1 bash[2497]: return await self.func(*args, **kwargs)
May 21 14:01:40 Lab1 bash[2497]: File "/home/pi/Bot/main.py", line 427, in petpet
May 21 14:01:40 Lab1 bash[2497]: from petpetgif import petpet # import petpetgif
May 21 14:01:40 Lab1 bash[2497]: File "/home/pi/.local/lib/python3.9/site-packages/petpetgif/petpet.py", line 1, in <module>
May 21 14:01:40 Lab1 bash[2497]: from PIL import Image
May 21 14:01:40 Lab1 bash[2497]: File "/home/pi/.local/lib/python3.9/site-packages/PIL/Image.py", line 134, in <module>
May 21 14:01:40 Lab1 bash[2497]: if __version__ != getattr(core, "PILLOW_VERSION", None):
May 21 14:01:40 Lab1 bash[2497]: NameError: name 'core' is not defined
how can i get the status from a user
!d discord.Member.status and you need the presences intent for this
property status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") instead.

or was it members intent idk
Hiii ares, so long
!e
code
Hello, passed like a month since i visited this channel lol 
Anyone got a clue that my bot suddenly started needing intents enabled and since I enabled it my bot just does not run any command, and it does not error anything, so I literally do not know how I can fix it
@client.command()
@commands.is_owner()
async def load(ctx, extension):
await client.load_extension(f"cogs.{extension}")
print(f'loaded {extension}')
cog aint loaded no errors neitheris there something printed in terminal
!e while True: pass
do you have an on_message event?
did you upgrade dpy?
I think I did upgrade discordpy
Is that bad or?
then you need to enable the message_content intent
intents.message_content = True
yes
Alright
#bot-commands
Ok
print something before loading the extension and see if the command runs
any help?
k
1 is printed
Error I get is
Exception has occurred: ExtensionNotFound
well, that file does not exist then.
But
show your file structure
@tasks.loop(seconds=30)
async def checkforvideos():
with open("youtubedata.json", "r") as f:
data=json.load(f)
print("Now Checking!")
for youtube_channel in data:
print(f"Now Checking For {data[youtube_channel]['channel_name']}")
channel = f"https://www.youtube.com/channel/{youtube_channel}
html = requests.get(channel+"/videos").text
try:
latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
except:
continue
if not str(data[youtube_channel]["latest_video_url"]) == latest_video_url:
data[str(youtube_channel)]['latest_video_url'] = latest_video_url
with open("youtubedata.json", "w") as f:
json.dump(data, f)
discord_channel_id = data[str(youtube_channel)]['notifying_discord_channel']
discord_channel_id = client.get_channel(int(discord_channel_id))
msg = f"<@&976169188274086019> {data[str(youtube_channel)]['channel_name']} Just Uploaded A Video Or He is Live Go Check It Out: {latest_video_url}"
await discord_channel_id.send(msg)
checkforvideos.start()
@checkforvideos.before_loop
async def checkforvideos():
print('waiting... 2 ')
await client.wait_until_ready()
@slash.slash(name="add_youtube_notification", description="admin only")
@commands.has_permissions(manage_roles=True)
async def add_youtube_notification(ctx, channel_id: str, *, channel_name: str):
with open("youtubedata.json", "r") as f:
data = json.load(f)
data[str(channel_id)]={}
data[str(channel_id)]["channel_name"]=channel_name
data[str(channel_id)]["latest_video_url"]="none"
#you can also get discord_channe id from the command
#but if the channel is same then you can also do directly
data[str(channel_id)]["notifying_discord_channel"]="975360118591991818"
with open("youtubedata.json", "w") as f:
json.dump(data, f)
await ctx.send("Added Your Account Data!") ```
!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.
How can I convert this to tiktok instead of YouTube
you have a folder cogs, inside it you have another folder named cogs, then you have antiswear inside that one
Yes
did you do !load cogs.antiswear?
I did ,load antiswear
Thats wrong
Can someone check this code? I can't seem to get it to work, I have enabled voice-state Intents and loaded the cog but it's not kicking me from the afk channel but I'm also not getting any errors unless my error handler is eating it (which I don't think is likely). The code is here https://paste.pythondiscord.com/rorenuxega because it's so long
kk
‘’’hi’’’
!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.
they are backticks
Correct
yeah, it does
Same
it does for every keyboard....
Oh wow fr??? Didnt know that
