#discord-bots
1 messages · Page 800 of 1
CTRL + SHIFT + P, then reload window
or just close it and open it, whatever you prefer
nope
thats not a disnake issue, your field value is empty
do what robin said
reloaded and still says ModuleNotFoundError: No module named 'discord'
God is here nvm

thx
I've had that sort of trouble since I installed 3.10 as well 
I think the packages are still being installed to the older version while the IDE uses 3.10 - they've changed the location where Python installs now 
ohhh, well then using a venv would be the best option
I personally use anaconda but I've heard people say it's bad
I've never had any issues
flag class:
class ItemFlag(commands.FlagConverter):
flags: list[str] = commands.flag()
command:
@commands.command()
async def setitems(self, ctx: commands.Context, *, items: ItemFlag):
error:
disnake.ext.commands.errors.MissingRequiredFlag: Flag 'flags' is required and missing
So, I got an issue with flags, I invoked the command with <prefix>setitems a=1 b=2 it raised an error. Any thoughts?
@commands.command(help = "Ratio a worthy foe")
async def ratio(self,ctx,msg_id):
for channel in ctx.guild.channels:
try:
msg = await channel.get_message(id)
except NotFound:
continue
I am trying to get a msg object when a message id is passed into the command. The end goal is then to have the bot react and "ratio" the message. But in order to add the reaction, i.e. msg.add_reaction() I need the message object, and I am struggling to get it
print('Bot: ' + get_response(input('You: ')))
I'm trying to get the bot to take every message and then reply to it, Same code above
@client.event
async def on_message(message):
if message.channel.id == 877066533250166824 :
channel = 877066533250166824
author = str(message.content)
while True :
await get_response(author)
await channel.send(get_response)
await client.process_commands(message)
and it's still not working
did you mean the author message or every message in the channel?
i want the user to copy the message id and then send it in, and then the bot create the message object for that message, regardless of channel. i want to ratio the copy_id message
Hello, I can't get my role adder to work here is a video explaining the problem. and the code
this may help
msg = await ctx.fetch_message(msgID)
input isnt very async
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@echo wasp Don't handle the error, it should raise one then
Remove your error handler for that command
It doesn't work like that
ok commented it out
Ohh, ok i'll try
also, in your code you have 2 args, but you only provided one
You need to give it a role and a member
while invoking
how to add slowdown
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
slowdown not cooldown
this in not it
ok but what if i want it to give it to the person doing the command
!d discord.TextChannel.slowmode_delay
The number of seconds a member must wait between sending messages in this channel. A value of 0 denotes that it is disabled. Bots and users with manage_channels or manage_messages bypass slowmode.
set default value for member in your arg to None, and then in your code member = member or ctx.author ig?
this will make the member arg not a required arg
ok so if i want to give someone else a role i can still do that
it will, youre just setting a value to it
yes if they provide an ID, then member will be the member they gave
yeah, and if it's not provided then it automatically takes the default value as the arg?
tf is kayle typing
fr
lol
he writing a whole paragraph
async def makenotes(ctx, *, args):
#try:
if (len(list(db.NoteBoyNotes.find({'_id':'{}'.format(ctx.author.id)}))) == 0):
NotesUpdateDict = {'_id':'{}'.format(ctx.author.id), 'notes':[]}
NotesUpdateDict['notes'].append(args)
NBNotes.update(NotesUpdateDict)
x = notesCol.insert_one(NBNotes)
await ctx.send("Ok, Noted")
else:
pass```
I am recieving the following error
```TypeError: 'AsyncIOMotorCursor' object is not iterable```
you cant iterate through a cursor
but how am i iterating without loops?
i restarted my bot and i still get this error
show code, you didn't give it a member
You are missing a required argument when invoking the command
@commands.command()
@commands.has_role(893308556596641792)
async def addrole(self, ctx, role: discord.Role, member: discord.User):
member = None or ctx.author
roles = [933104091066941530, 936481481113632839, 936712347211419708, 936712664950931476, 842254098266718219, 842253873376264222, 842254463309316136, 842260259417489448, 842260429044842572, 893308041699680337, 816838497159610369, 826636738306506794, 841144860966125568]
if role.id in roles:
await member.add_roles(role)
await ctx.channel.send(f"You have added {role} to your role list!")
#@addrole.error
#async def addrole_error(self,ctx,error):
# if isinstance(error, commands.RoleNotFound):
# await ctx.send("I Can't give you that role because either it is not on the list or it is not a role")
```
!e
def function(name: str) -> str:
return name
function()
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 4, in <module>
003 | TypeError: function() missing 1 required positional argument: 'name'
well u didn't do what I said
i did half i am thinking
don't make custom command errors, handle the errors inside of the command
what
what was that just add a defualt value in params?
don't judge me it's hard on mobile
!e
def a(name: str = "bob") -> str:
return name
a("pepe")
a()
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
it would return pepe and then bob lol
@commands.command()
@commands.has_role(893308556596641792)
async def addrole(self, ctx, role: discord.Role, member: None):
member = None or ctx.author
roles = [933104091066941530, 936481481113632839, 936712347211419708, 936712664950931476, 842254098266718219, 842253873376264222, 842254463309316136, 842260259417489448, 842260429044842572, 893308041699680337, 816838497159610369, 826636738306506794, 841144860966125568]
if role.id in roles:
await member.add_roles(role)
await ctx.channel.send(f"You have added {role} to your role list!")
``` Please explain when i added what i thought you ment and it is still requireing member
why did u typehint it
okimii
hi
not u
go touch grass
oh
maskuh typehinted member to None
hi again-
it's like, what, 3 am at yours
its 2am🙄
lol
sleep
10 30 pm here
no
12 pm
kayle stop typing already😭
should i just delete the whole thing in the bar?
6:30am
what bar...?
foo bar
async def addrole(self, ctx, role: discord.Role, member: None): ``` this bar and remove member typehint
I'm gonna go attend my class
@slate swan help him if u can
sure
you dont type hint like that
i mean you do but not like that
youre just saying member is expected as None
to add a default value it would be as so
member: discord.Member = None
member: discord.Member = None
member = member or ctx.author
i had py async def addrole(self, ctx, role: discord.Role, member: discord.User):
ooooooooooooooooooooooooooooohhhhhhhhhhhhhhhhhhhhhhhhhhhh now that makes sense
what would go in the reactrole.json file? i dont know what to start help.
@bot.command()
@commands.has_permissions(administrator=True)
async def reactionrole(ctx, emoji, role: discord.Role, *, message):
embedVar = discord.Embed(description=message)
msg = await ctx.channel.send(embed=embedVar)
await msg.add_reaction(emoji)
with open('reactrole.json') as json_file:
data = json.load(json_file)
new_react_role = {
'role_name':role.name,
'role_id':role.id,
'emoji':emoji,
'message_id':msg.id
}
data.append(new_react_role)
with open('reactrole.json', 'w') as j:
json.dump(data,j,indent=4)```
can u stop repeating your question? if someone knows the answer they will respond. please stop
wdym? i sent this once u can read chats.
i was just going to say that but i didn't because i am the one getting
twice
?
they have logs, this will not work and I am not dumb
removes msg
yes
i didnt call u dumb
lol
u insinuated it
no, i just lied lmao
deletes all messages
i only sent it once!!
guys stop fighting
sure i go to my class lol
i didnt say that exactly but u do u
true
whats wrong? or what do you want to achieve
what isnt?
how to make so that after the user uses a command, the next message they sent will be set to a veriable
using json as a db
hi, so i have coded a reactionrole command but i dont know what to add or code in the reactionrole.json file.
YOU FIXED IT THANK YOU!!!
just set the wait_for in a var thats how its done iirc
np
well didn't you already add the data in the json file?
set it as an instance variable to your bot or a mapping of some kind. also, fyi, naming embedVar to embed and doing send(..., embed=embed) is perfectly legal lol
How can i learn to build gpt 3 bots as a complete beginner?
also i want it to delete the 2 messages after like 10 seconds how would i do that i think with asyncio.sleep(10) then await ctx.message.delete(2) or something like that
im going to go to sleep gn guys have a lovely day or night❤️
can i have a exampole
for a message
not a reaxtion
var = await bot.wait_for()
oh
hey okimii can you answer my question above?
!d discord.abc.Messageable.send | just use the delete_after kwarg for both msgs
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
oh, and is there a alternative way of finding the user guild name without member.guild.name
the name of the guild of where the member is in?
or?
yep
yo
what is attrs
attributes
can i know the other way
explain? like example
define good
wait html is a python library
idk
i just said random stuff but like the basqics
loops, functions, if else
boolean
it could be like an addon but html is a whole different coding language
not sure if there is?
@steep ocean #python-discussion
i tried already
ngl
i pretty much need like someone to carry me thourgh a few coding lessons on code hs so i can get rid of my d
await ctx.send("text", delete_after=10)
but i also want it to delete the message the user sent
you don't need an example on how to use kwargs.. you should've learnt that before using d.py
well your method works lol just use .purge
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
nice
does guild.name work
okimii do you have spare time to help a poor little soul get a better grade in his computer hardware class that he currently has a D in and his last effort to do this is tohinght by 12 am
not really im failing math😭
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
might help
?
website for beginners etc
i would love to look at this but i am in a panick, and i need this done like soon and im too dumb to understand this stuff
ive tried for weeks and cant do it
i mean i could give you short explanations in ot channels if you want only for like 10mins
umm sure
just ping me in one
what is ot channel
!OT
oh
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
isnt case insensitive for a reason
yes
i have a members id list i want to check if member.mentioned_in(message)
flag class:
class ItemFlag(commands.FlagConverter):
flags: list[str] = commands.flag()
command:
@commands.command()
async def setitems(self, ctx: commands.Context, *, items: ItemFlag):
error:
disnake.ext.commands.errors.MissingRequiredFlag: Flag 'flags' is required and missing
So, I got an issue with flags, I invoked the command with <prefix>setitems a=1 b=2 or <prefix>setitems a:100 b:200 it raised an error. Any thoughts?
Two approaches:
-
You run a for-loop for each element of the list, looping to fetch the member and checking if they're mentioned in the message
-
You get the mentions of the message via
message.mentions, run a for-loop to compare the ID of each object with the IDs mentioned in the list
If the "member list" you have is just a few elements, then the first method would be preferable
yes i want the mentioned id
@timid wagon i have user id
i want member.mentioned_in(message):
member .
member = id
So you use the first method
id is in AFK = []
Fetch the member via the ID in the list first
await bot.fetch_user(AFK)
You read through this, right?
ya
``py
for member in AFK_PPL:
user = bot.fetch_user(AFK_PPL)
if user.mentioned_in(message):
await message.reply(f"||{member}|| | is AFK")
You having trouble with that?
That is the basic example, yes
yrah
You should probably return after the first instance, or check for all AFK users and then send a message at the end
What's the error?
no error
Is it printing aca or not?
Also, check if you have set a system channel for your test guild - otherwise guild.system_channel shall return None (though that would also give an error)
now it worked i had to do something in dashboard
but still its now what i wanted
the heart emojis arent showing up
@timid wagon discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In user_id: Value "[852911179450023976]" is not snowflake.
wdym
U sent a list, not an ID
ya i have a list of user
that need to be checked
can anyone help me with this
Code
@maiden fable';
Then use indexing
how to allow FlagConverter to take any flag name and value?
it is nice when you can copy pasta your command you built above and just change like 5 words and it does the opposite of the command you copy pasta does
user = await bot.fetch_user(AFK_PPL[0][0])
why 2?
Cz AFK_PPL[0] returns a list
Weird
File "c:/Users/hp/Desktop/bot/sluppy.py", line 289, in on_message
user = await bot.fetch_user(AFK_PPL[0][0])
TypeError: 'int' object is not subscriptable
Try printing AFK_PPL[0]
ok
Okay
It can simply be print(AFK_PPL[0])
@commands.guild_only()
@bot.command(name="afk")
async def afk(ctx, * , reason=None):
afk = f"[AFK] {ctx.author.name}"
try:
try:
await ctx.author.edit(nick=afk)
ids = ctx.author.id
AFK_PPL.append(ids)
await ctx.reply(f"||{ctx.author.mention}||| Set u AFK Reason : {reason}")
except:
ids = ctx.author.id
AFK_PPL.append(ids)
await ctx.reply(f"||{ctx.author.mention}||| Set u AFK Reason : {reason}")
except discord.DiscordException:
path
@bot.listen()
async def on_message(message):
if message.author == bot.user:
return
elif message.author.bot: return
else:
for member in AFK_PPL:
user = await bot.fetch_user(AFK_PPL[0][0])
if user.mentioned_in(message):
await message.reply(f"||{member}|| | is AFK")
@bot.listen()
async def on_message(message):
if message.author == bot.user:
return
elif message.author.bot: return
else:
for member in AFK_PPL:
if member == message.author.id:
try:
AFK_PPL.remove(message.author.id)
await message.author.edit(nick=None)
await message.channel.send(f"||{message.author.mention}|| | I removed u AFK")
except discord.DiscordException:
path
full afk command(nvmd)
779990652149825537
is the list
Mhm
@bot.listen()
async def on_message(message):
if message.author == bot.user:
return
elif message.author.bot: return
else:
for member in AFK_PPL:
user = await bot.fetch_user(AFK_PPL[0][0])
if user.mentioned_in(message):
await message.reply(f"||{member}|| | is AFK")
causing error
if i ping the afk user
it return this
Why fetching?
u said
ah sorry @timid wagon said
So u just want a behavior like *args?
i was alsi thinking why fetch
Hey @slate swan! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
Communities
The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.
get_user
class discord.ext.commands.FlagConverter```
A converter that allows for a user-friendly flag syntax.
The flags are defined using [**PEP 526**](https://www.python.org/dev/peps/pep-0526) type annotations similar to the [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses "(in Python v3.9)") Python module. For more information on how this converter works, check the appropriate [documentation](https://discordpy.readthedocs.io/en/master/ext/commands/commands.html#ext-commands-flag-converter).
iter(x) Returns an iterator of `(flag_name, flag_value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
This is a Python support server, not JS
Communities
The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.
huh?
you could say so, I want to be able to do <prefix>cmd a:1 b:2 someotherarg: 10 to take any arg without seeing the name
await ctx.send(AFK_PPL[0])
ok
Lemme see...
Wait
Try doing *args: FlagConverter
instead of emty list it show error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range
The list is empty
in the command arg?
yes
[] why not sending
@maiden fable its working fine now
time waste for this
Yes
Cool
@nimble plume :white_check_mark: Your eval job has completed with return code 0.
hello world
<prefix>cmd a:100 b:200 tried to invoke using this, but when I print the arg, it returns empty stuff
Rip
@visual island
what's with that
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, channelid, YourUser: disnake.Member):
with open(f'{YourUser.guild.name}.txt', 'w') as e:
e.write(channelid)
why does it not work
that only allow flag named member
ok
does just guild.name work?
import os
import dotenv
from init import client
dotenv.load_dotenv()
token = os.getenv("TOKEN")
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
# Importing Commands
from bot_commands.moderation_commands import lockdown
@client.command()
async def test(ctx, arg):
await ctx.send(arg)
client.run(token)
I am setting up a discord bot
but none of these commands are working
I don't understand why?
Srll doesnt work
Maybe i should make a databse
oh
you upload/open your file there
i have a role mute
Guys I saw that discord.py sends wrong url to the discord api so I downloaded it from pypi and fixed it but it still sent wrong data (I deleted the discord.py and edited the new one). So I started finding a way to change presence update using requests but no clue what to do, can anyone help please
what error?
\👍
define client
i've imported it
@nimble plume fiddler blocks discord api from connecting, and IDK about wireshark or tcpdump, can you help finding what request does the cmd send when changing bot presence
sry cant help
I mean its not a big project, just like friends can you find because "ghar me light ni hai :("
how do i get a role top_position
wdym?
i want to compare a mute role with author.top_role
is it possible to have a command that functions on it's own but also have a subcommand? /a -> ... - /a b -> ...
try to get the list of the authors role and print the result, then see if the first role is highest or the last, then you can automate it the next time
i want to compare a mute role with author.top_role
help
i want to compare a mute role with author.top_role
What would bring the best mix of performance, security & stability:
- When my bot has a single database for each server it's in
- "Just" a single database with different tables for each server
- One single table for all servers settings?
1 table, unlimited rows & columns
i have made a nickname all command but it gives this traceback, here is the code ```py
@client.command()
async def nick(ctx):
for member in ctx.guild.members:
await ctx.edit(nick="𝚃𝚛𝚊𝚐𝚒𝚌𝙲𝚘𝚖𝚎𝚍𝚢𝟿/𝟷𝟷")
using discord.py
Currently I am storing api key and bot token in a json file. If I am using a vps should I consider using .env file to store these private key. If yes . why ?
Hello!! Can I auto_archive after 1 hour in disnake using the create_thread function?
yes
It seems only allowing 1 minute, 1 day, 3 days or 7 days
if ctx.channel.permissions(ctx.guild.default_role, send_messages=True):
Why this isn't working?
ugh sometimes i hate cogs
i messed nothing with it just added code properly under the init
no code in the line of sight to the top
There is no permissions method?
how do i make it where someone makes there status a certain word or sentence it sends a message
You're probably looking for channel.set_permissions @stiff anvil
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
`import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print('ready')
@client.command()
async def ping(ctx):
await ctx.send(f'pong {client.latency}')
@client.command()
async def register(ctx):
file = open('accounts.txt','w')
file.write('register')
file.close()
await ctx.send('Account registered')
`
i cant write on the text file
so just a vscode glitch?
From what I know, yes
how do i make it where someone makes there status a certain word or sentence it sends a message
Please don't resend the question
response.content.endswith()
What you're probably looking for is to check their activity or status @trim fulcrum
am i do it right?
how would i fix?
You have to use the status's name
i did
As I said, before is a member. Not the member's status
something to do with my except
what youre probably looking for is before.status instead of just before
Btw Status refers to idle, dnd, etc. So that shouldn't apply here
how to react on message?
!d discord.Message.add_reaction
await add_reaction(emoji)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
You must have the [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permission to use this. If nobody else has reacted to the message using this emoji, the [`add_reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") permission is required.
then how would i make it to like my status
like where u put words
ah ok should it be raw_status then?
kind of unsure
async def buy_this(user,item_name,amount):
item_name = item_name.lower()
name_ = None
for item in self.mainshop:
name = item["name"].lower()
name_ = name
price = item["price"]
break
if name == None:
return [False,1]
cost = price*amount
users = await self.get_bank_data()
bal = await self.update_bank()
if bal[0]<cost:
return [False,2]
try:
index = 0
t = None
for thing in users[str(user.id)]["bag"]:
n = thing["item"]
if n == item_name:
old_amt = thing["amount"]
new_amt = old_amt + amount
users[str(user.id)]["bag"][index]["amount"] = new_amt
t = 1
break
index==1
if t == None:
obj = {"item": item_name , "amount" : amount}
users[str(user.id)]["bag"] = [obj]
except:
obj = {"item": item_name , "amount" : amount}
users[str(user.id)]["bag"] = [obj]
with open("mainbank.json","w") as f:
json.dump(users,f)
await self.update_bank(user,cost*-1,"wallet")
``` And idc that i am using a json data base so don't tell me to not use a json data base
The solution would be to
- Check if the user has an activity
- Check if the activity is of discord.CustomActivity type
- Match the content with an if check, and then run the code.
cc: @trim fulcrum
ok
so before.custom_activity?
The except block should be at the same indent as the try block
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activity’s hash.
str(x) Returns the custom status text.
New in version 1.3.
before.activity
ohhhhhhhhhhhhhhhhhhh thank you
ok
It sends details of message from list instead of storing message itself
Then you can use something like if isinstance(s, discord.CustomActivity):
Then a content check, and initiate your code
who is this for
u are appending the message object, append the content only
me
message.content
append.message.content?
ah
or response.content in your case
okay wait lemme check
@_join.before_invoke
@_play.before_invoke
async def ensure_voice_state(self, ctx: commands.Context):
if not ctx.author.voice or not ctx.author.voice.channel:
raise commands.CommandError('You are not connected to any voice channel.')
if ctx.voice_client:
if ctx.voice_client.channel != ctx.author.voice.channel:
raise commands.CommandError('i am already in a voice channel!')
ctx.message.add_reaction('✅')
def setup(bot):
bot.add_cog(Music(bot))
read the error...
i didd
Okay thanks it worked.
Pretty sure you can't use multiple decorators for the same function
Alrighty
You can!
Well then, TIL
me who uses 6+ decorators on a single function
You have an empty function above that function
most probably
okay
could you show code above that function?
im too lazy to add commands.guild_only() decorator to all the commands is there a faster way 😔
when should I consider using sharding ? My bot is now in 200 servers should I start using like 2 shards ?
btw where is the appendage stored?
You don't need to shard it until 1k servers, 2.5 is recommended
There is if you use disnake 
That is if you want all your commands to be limited to a few guilds
ofc I do!
Appended response will go away if the script shuts down. So I need a place to store the responses in the list without losing the appends.
What code do you have above the decorator
@quick gust https://guide.disnake.dev/getting-started/creating-commands#registering-commands-in-specific-guilds
Isn't it only for slash commands?
because u are sending the whole list lol
Works for all commands iirc
I know I'm printing the list. Now there is a list that has something.
Uhhh I'll confirm again then
"".join([i for i in response_list])
i didnt understand
but i want to store whatever is in the list
@quick gust is this good?
and they want the command to not function in dms lol
for slash's only I believe
say, there is a response. The response is stored in the list.
But if I shut down the bot
ah yes
The response won't be in the list anymore
use a db, since the list items are stored in the cache
not really, u can use any async db
async db
postgresql
Still wouldn't work - before.activity is an activity object, not a string
^
not async db
o
but a db that has an async driver/bridge
There's also the fact that a user can have multiple activities, so you would have to cover for that case
how can i make it like if this status says like this
postgresql i suppose
To elaborate on what I recommended earlier:
async def getcustomstatus(user):
for activity in user.activities:
if isinstance(activity, discord.CustomActivity):
# Do stuff here```
sure, u can use asyncpg then
cc: @trim fulcrum
and then what?
where can i learn about it
learn sql first
how long would that take
not alot, sql is pretty easy
Then you just apply it :P
but I have a slight feeling you lack the basic python knowledge, if so I really recommend learning python first as discord.py is a somewhat complex library (!resources in #bot-commands)
I'm pretty sure you understand how to use it in the member update event now
your event name...
dk if this related but i change to a new PC, and dis happen, what did i missed
those reds are no module named
wdym
These are libraries you need to pip install yourself
:v ok
pip install discord
ok ty
how to set role.edit(position=max) max that it possible
@client.slash_command(description="Set up a mod log channel.")
async def SetModLog(ctx, channelid, member: disnake.Member):
client.mongo = motor.motor
client.mongo.connect(host='mongodb://GrowSuperPro:<password>@cluster0-shard-00-00.j7jsz.mongodb.net:27017,cluster0-shard-00-01.j7jsz.mongodb.net:27017,cluster0-shard-00-02.j7jsz.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-p9fsfe-shard-0&authSource=admin&retryWrites=true&w=majority')
client.mongo.myFirstDatabase.modlog.insert_one({"channelid": channelid, "member": member})
embed=disnake.Embed(color=0x00d60e, title="Successfully set up the mod log channel.", description=f"Successfully set up the mod log channel: {channelid}.")
await ctx.send(embed=embed)
``` does this work
try it
no
I have been somewhat successful in creating command for storing questions from users in the form of a list. Now, since its for a quiz, how can I make it that the users can give options and decide what is the correct option as well. Would using a dictionary instead of list work better?
I guess you can have a dictionary of formatpy {question: [correct_answer, incorrect_answer, incorrect_answer]
So likepy {"Who was the first president of the united states?": ["George Washington", "Abraham Lincoln", "Barack Obama"]}
You know the correct answer is always index 0, so you compare against that
yes but how would I go about with making custom questions then?
Because the reason I used list was so that I could append
guys what must I do to prevent errors when a user types just a command without parameters?
You just do the dictionary equivalent. questions_dict['question'] = ['correct answer', 'incorrect answer', 'incorrect answer']
ooh
-
handle the error, you can use the
on_command_errorevent and check if theerroris aMissingRequiredArgumentsinstance, if it is then you just pass -
or you can make a error handler for a particular command only
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
!d disnake.ext.commands.Bot.on_command_error
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
thanks guys 🙂
how to allow FlagConverter to take any flag name and value?
icy has been asking since morning 😔
yeah 😔
Hey @sullen pewter!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Oh wait u are icy lmao
Maybe ask in the d.py server
that's not what I want
did that, but the server is dying
You can always pass in a string type
so what I want is: for example I have a FlagConverter class. Currently they can only take flags that's defined as the class's attribute. But my problem is, how to allow any flag name to be taken too
disnake.ext.commands.errors.ExtensionFailed: Extension 'lib.cogs.WildRift' raised an error: ImportError: cannot import name 'WRUser' from partially initialized module 'lib.Games.WildRift.User' (most likely due to a circular import)
What the hell is this?
Ah
Your file name
one week ago it worked perfectly
class Foo(commands.FlagConverter:
foo: str = commands.flag()
!cmd foo:123 works fine
!cmd bar:123 doesn't work
Hmm
I want the converter to catch every flag that's in the message
any idea?
Try using the dict type hint? Idrk
never use circular imports lol
It supports dict?
So the on_reaction _add doesn't work without running a command?
Most probably u got an if statement which is blocking the event
disnake.ext.commands.errors.MissingRequiredFlag: Flag 'flags' is required and missing still this
with dict and !cmd a:100
!d discord.ext.commands.flag
discord.ext.commands.flag(*, name=..., aliases=..., default=..., max_args=..., override=...)```
Override default functionality and parameters of the underlying [`FlagConverter`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.FlagConverter "discord.ext.commands.FlagConverter") class attributes.
the beta-testing channel is dead
I can't ask in #help
done.
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
O
what is dis
!pypi chardet
Re trace enviromental variables
No
Reaction object
when did u change nickname
I didn't tho
Long time ago he did
:V ok
Is it possible to change the time-out duration of a Disnake View?
ERROR:no matching distribution
#discord-bots message @maiden fable
Yes
Views are same so no need to simplify "Disnake View"
Wrong file name inputted
can I make so the bot will execute a code on the terminal? 
otuside the python environment obviously 
ERROR: No matching distribution found for PIL
ERROR: No matching distribution found for request
If its a cog yes
Its pillow
Huh?
Not pil
oh right, ok
!d eval
eval(expression[, globals[, locals]])```
The arguments are a string and optional globals and locals. If provided, *globals* must be a dictionary. If provided, *locals* can be any mapping object.
!d exec
exec(object[, globals[, locals]])```
This function supports dynamic execution of Python code. *object* must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs). [1](https://docs.python.org/3/library/functions.html#id2) If it is a code object, it is simply executed. In all cases, the code that’s executed is expected to be valid as file input (see the section [File input](https://docs.python.org/3/reference/toplevel_components.html#file-input) in the Reference Manual). Be aware that the [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal), [`yield`](https://docs.python.org/3/reference/simple_stmts.html#yield), and [`return`](https://docs.python.org/3/reference/simple_stmts.html#return) statements may not be used outside of function definitions even within the context of code passed to the [`exec()`](https://docs.python.org/3/library/functions.html#exec "exec") function. The return value is `None`.
and da request?
guys which system do you think is the hardest to make in discord bots?
How? I haven't been able to find anything in the docs...
U met me once in codm server and u said u didnt remember me so i was just showing u ur msgs
multiplaer arena IG\
Ah, I do remember u now (:
Pip install requests
haha exception to games
aproved on top.gg
Lol xD
ah what?
Wdym
aight gty
and bug on gramar mistakes or "(" not matching on 10 "("s
nice! ^^
how to fix lag
Wdym
Depends which type of lag?
PC lag
Buy new pc
ezpz
clean your temp folder, remove junk, that fun stuff
new bug detected! no money was found
But that's not on topic with this channel
"that fun stuff"
ig i am gonna make a discord bot in go or rust lol
lol
one advide, don't go to replit
Can you even do that?
is what u think is same as mine?
Ok
ofc, why not?
one solution found! gimme money
python is awesome but i am looking for some projects and am a bit bored to make bots in python so yea thats why gonna switch to those langs
no JS ples
i have coded bots and website in js, tbh js really sucks
like i dont hate that lang but dont like it either
Yep, there's a ton of Discord Libraries for a number of languages, so Discord.NET for .NET, Serenity for Rust, DiscordGo for Go, uhh there's a few others but that's all I remember
how do i put sticker on embed value
Sticker or emoji?
He means an emoji since bots can't use stickers
I know, I asked just to confirm because people ask weird questions all the time
He also showed a pic and it's an emoji, so most probably he just wrote that in a hurry
who knows
I do idk
Lmao
yeah ikr im dumb 🙂
wut
oh
Just copy paste this in yr code
ok" and i will see
!d discord.RawReactionActionEvent
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
ah i see, THX
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
#bot-commands
ohkk
guys, what's the @ used for in discord.py?
For mentioning people?
What's that? Does it have any use without libraries?
Nested functions, yes
@ivory pelican
def with_commit(func: Callable[P, R]) -> Callable[P, Awaitable[R]]:
async def inner(*args: P.args, **kwargs: P.kwargs) -> R:
await commit()
return func(*args, **kwargs)
return inner
This is an example of a custom decorator (with extra static typing)
omg cant understand a single thing that's going on lol
might have to study the fundamentals before trying to build my bot
i was attempting to make my db utility file async, but it didn't quite work so i scrapped it lmao
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
How do I change the default_role to a role I want?
the default role is @everyone i believe
not sure if you can change it
!d discord.Guild.default_role
property default_role: discord.role.Role```
Gets the @everyone role that all members have by default.
bruh
it's "moyai", not "moai"
I want to use another role
What should I do?
adding a role?
NOOOO
.
I'm trying my best
hmm
...?
it's kind of hard to dig up stuff, most of the things I'm finding is ctx.guild.default_role
exactly...
I'll look in the docs
ik I'm reading it rn
<3
lol
@bot.command()
async def vip(ctx):
if ctx.author.id == 626127081419571206:
a = ctx.guild.members
c = bot.get_channel(938864264498778122)
r = ctx.guild.get_role(924798354796474439)
for b in a:
if b.activity is None:
pass
else:
if "/club" in b.activity.name:
await b.add_roles(r)
await c.send(f"Le he dado el rol vip a {b}. ")
else:
pass
else:
pass
I'm trying to make a command to give vip to everyone who has a vanity url in status, I get this error:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'NoneType' is not iterable
send the full error
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 46, in vip
if "/club" in b.activity.name:
TypeError: argument of type 'NoneType' is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: argument of type 'NoneType' is not iterable
sarthak is here
What r u trying to do?
.
Edit a role's permission in a channel?
I'm SamTheNoob btw
yes!!!!
can someone help?¿
!d discord.abc.GuildChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
how tf do I use it?
channel.set_permissions(role, overwrite=PermissionOverwrite ())
role should be a string?
the permission overwrite would be defined by yiu
or a var?
PermissionOverwrite () 
A role object
kk ty <3
lol
the space doesn't matter
b seems to be none. Try printing the type of b
yeah ik it's just weird
I'm on phone so...
I think it's pretty obvious
since you don't bother to use the backticks
the user has no activity,
or you don't have presences intents enabled
Hey, i want to make a music bot but like i don't want to use youtube cause of the issues and etc
i am not sure if you can stream spotify songs via discord bots or not cause ig i read somewhere that you can't
so i was wondering how do the bots like hydra and etc play songs? like is there a platform that allows us to stream songs without downloading them and etc?
yes but did: if b.activity is None: pass
please show code
here
a is None, do you have member intents?
yes
1 minute
okay
The name of the activity.
Yea it can be None
@commands.command()
@commands.has_permissions(administrator=True)
async def hide(self, ctx):
role = self.client.get_role(939081396352319500)
await ctx.channel.set_permissions(role, view_channel=True)
await ctx.channel.edit(topic="This channel is currently Hidden!")
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'get_role'
idk why
get'role is a method of guild
Does the user have a status?
how do I get guild?
it checks every user on the guild
get_guild exists
if the user doesnt have a status its none
not true, member.activity always be None
Like if a user has an emoji in status, but not a text
It would still be a value
!d discord.Member.activity
property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
it is None if no activity is done
^
@bot.command()
async def vip(ctx):
if ctx.author.id == 626127081419571206:
a = ctx.guild.members
c = bot.get_channel(938864264498778122)
r = ctx.guild.get_role(924798354796474439)
for b in a:
if b.activity is None:
pass
else:
if "/club" in b.activity.name:
await b.add_roles(r)
await c.send(f"Le he dado el rol vip a {b}. ")
else:
pass
else:
pass
I did if the activity is None pass, if its not it checks if u have /club and if u dont it passes
so idk why its wrong
imagine a condition in which user has an emoji in status,
so the activity is None statement is ignored
But the user still does not have an activity name
Similar to what I have rn
you can just add a statement py if not b.activity.name : pass inside the else
I have this code:
@bot.event
async def on_member_join(member):
channel bot.get_channel(930108508274298950)
welcomembed=discord.Embed(title = "Welcome" + member.name, colour = discord.Colour.random())
await channel.send(embed=welcomembed)```
and i can't find the error
channel =
oh
lol
And the parameter is color ig, idk if colour works
now there is error with the await
What error
okayy
Cap
🗿
🗿
unindent does not mach any outer indentation level
Check your indents, something is too far indented
u mean the tabs?
where every line is
bingo
i found it
The channel variable is badly indented
thanks
hm
how to make a mod logs sytem
do u know?
we won’t spoon feed
know what?
all you need is a log channel and a way to send something there after the command is invoked
is it considered Advanced btw?
Yes
i want the user to set which channel they want it to be in, i heared you must use a database but i dont know how to make one
i have it installed but idk how to use
you just make a database which saves id of the channels relating with the id of guild
sqlite broswer
!pypi aiosqlite
Not the browser mate, you need to create a db file
^
the browser creates one
Still preferred to create it with code
reas aiosqlite docs
!d sqlite3.connect this creates the database automatically
sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])```
Opens a connection to the SQLite database file *database*. By default returns a [`Connection`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection "sqlite3.Connection") object, unless a custom *factory* is given.
*database* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the database file to be opened. You can use `":memory:"` to open a database connection to a database that resides in RAM instead of on disk.
When a database is accessed by multiple connections, and one of the processes modifies the database, the SQLite database is locked until that transaction is committed. The *timeout* parameter specifies how long the connection should wait for the lock to go away until raising an exception. The default for the timeout parameter is 5.0 (five seconds).
aiosqlite
ok
Async bridge
async with aiosqlite.connect(...) as db:
await db.execute("INSERT INTO some_table ...")
await db.commit()
async with db.execute("SELECT * FROM some_table") as cursor:
async for row in cursor:
...
this has to be in a command?
ok
https://www.youtube.com/watch?v=o-vsdfCBpsU& I'll recommend this
Welcome to an SQLite mini-series! SQLite, as the name suggests, is a lite version of an SQL database. SQLite3 comes as a part of the Python 3 standard library.
Databases offer, typically, a superior method of high-volume data input and output over a typical file such as a text file. SQLite is a "light" version that works based on SQL syntax. SQ...
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS channels(guild_id INTEGER, channel_id INTEGER)")
conn.commit()
this could create it properly? cause
no
ok
a connection hasn't been established
its over
conn = sqlite3.connect('channels.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS channels(guild_id INTEGER, channel_id INTEGER)")
conn.commit()
oh wait the guild_id is just to create a new table name, and not the real guild id?
i'd use aiosqlite though. you can turn that to
Is it possible to make it so that when a participant left, it was written how long he was on the server in time? if yes, can you tell me how?
async with aiosqlite.connect('channels.db') as db:
await db.execute("CREATE TABLE IF NOT EXISTS (guild_id INTEGER)")
await db.commit()
@slim ibex It is for me?
no
@slim ibex help pls
.
!d discord.on_member_remove
discord.on_member_join(member)``````py
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
to find the time, you might need to use the datetime module or something
ok
@slim ibex it is for me now?
?
commit is necessary?
commit saves to the db so i would do it
ok
so it will be in a command?
are you subclassing the bot, because you can make the db connection a method that runs on the on_ready event
otherwise, you just need it to be a function
wdym by subclassing
.
class Bot(_BotBase)
no
inside the () is a super class (parent class)
its not in a subclass
conn = aiosqlite.connect('channels.db')
c = conn.cursor()
def create_table():
c.execute("CREATE TABLE IF NOT EXISTS channels(guild_id INTEGER, channel_id INTEGER)")
def data_entry():
c.execute("INSERT INTO channels VALUES(1983383, )", (ctx.guild.id, ctx.channel.id))
im not sure how to change this to aiosqlite
you can connect in a procedural way instead of context managers.
db = await aioqlite.connect(...)
cursor = await db.execute(...)
who ghost pinged me
idk
nope
decorators are an advanced topic?
how to make the code i wrote into a command
cause when i do the def
in a command
its pretty easy to learn once you get how it works
yeah it is, but it is still somewhat advanced
yep
cause when i do def in a command it says not accessed
i would learn SQL before attempting anything database related
and there are also docs to read
i am watching a video
where to lkearn it
can you show me a good one
GeekForGeeks
Hi, i have an error AttributeError: 'NoneType' object has no attribute 'send'
My code is:
@commands.Cog.listener()
async def on_member_join(self, member):
cursor = await self.db.cursor()
id = await cursor.execute(f"SELECT channel_id from audit Where guild_id = ?", (member.guild.id,))
channel = self.bot.get_channel(str(id))
em = discord.Embed(title="Member Joined", description=f"The memeber {member} joined!")
em.set_image(url=av)
await channel.send(embed=em)
Idk why
Your db is returning None for the channel object
Read the error
I know... How do i fix this
.
Possibly logging the time they joined and left, and calculating the difference via the datetime objects
@timid wagon
...use the correct SQL command?
bruh
That's what the error indicates atleast - the db didn't return an ID
Thanks
Or, actually, the ID that was returned doesn't refer to a channel
Yep
I believe it should be WHERE instead of Where
or the ID stored is wrong
FROM
WHERE
Can you suggest a start?
Ur turning the id into a string. It should be an int
and that ^
Try using the on_voice_state_update event
discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceState "discord.VoiceState").
The following, but not limited to, examples illustrate when this event is called...
before and after are VoiceState objects
Fun Fact: SQL returns tuples, not int/str
try doing id[0]
TIL
???
Uh, "today I learned"
Ah
Well then, I'll only respond to SQL-related problems once I learn it :P
Also IDs are int, not str
have we not figured what they're doing wrong already? they've not capitalised FROM and WHERE and they are doing str() while getting the channel
so do int(id[0])
Oh, I must have missed those parts sorry
Np
FROM and WHERE dont need to be capitalized for it to function
it can also return a list right?
or just a tuple
we do not need a voice, but when a person leaves the server, it is necessary to show how many times he was on the server
Huh
ye but its proper syntax
So you need to log their active-ness on the server, not necessarily their voice activity
That's why I said for it to function
pep8 for sql
It's bad practice but it will work
Oh tnks man@timid wagon
mhmm
It will always return a tuple, which may he a list of tuples too ( as in fetchmany/fetchall() methods
ye that's what i was asking, ty
Eh nvm, I was wrong
It's quite the opposite
oh lol
cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a list of tuples. An empty list is returned if there is no record to fetch.
I'm confused again 💀
💀lemme have a break
🥴
Is correct.
!PyPi ANSI would it be able to make a ANSI string to send in discord
q = {
"question" : [],
"options" : [],
"answer" : []
}
question = q["question"]
options = q["options"]
answer = q["answer"]
@client.command()
async def ttrivia(ctx):
await ctx.send("Input your question here")
rresponse=await client.wait_for("message", timeout = 30)
if rresponse.content.endswith("?"):
await ctx.send("Your response has been stored")
else:
return await ctx.send("Entry denied")
await ctx.send("Input your options here")
rrresponse=await client.wait_for("message", timeout = 30)
if rrresponse.content.endswith(""):
await ctx.send("Your options have been recorded")
await ctx.send("Insert your answer here")
rrrresponse=await client.wait_for("message", timeout = 30)
if rrrresponse.content.endswith(""):
await ctx.send("Your answer has been stored")
question.append(rresponse.content)
options.append(rrresponse.content)
answer.append(rrrresponse.content)
@client.command()
async def quiz(ctx):
await ctx.send(random.choice(question))
if question==answer and question==ctx.wait_for("message", timeout = 30):
await ctx.send("Your answer is correct")
else:
return await ctx.send("Your answer is wrong")
@client.command()
async def dict(ctx):
await ctx.send(q)
it does not wait for output 😞
em.add_field(name="Member created at:", value=member.created_at.timestamp())
It returns <built-in method timestamp of datetime.datetime object at 0x0000022D732B0C90>