#discord-bots
1 messages · Page 1098 of 1
color,string=getattr(discord.Color,['green','red'][(l:=random.randint(0,30))>20]),f"ok{'sus' * l}ok"
@spi.command()
async def pp(ctx):
size= random.randint(0, 9)
color = None
pp_string = f"8{'=' * size}D"
if size> 5:
embul=discord.Embed(title="PP calculator",color=discord.Color.red())
embul.add_field(name=f"Your pp length\n{pp_string}",value="This is not a random response.")
await ctx.channel.send(embed=embul)
else:
embul=discord.Embed(title="PP calculator",color=discord.Color.red())
embul.add_field(name=f"Your pp length\n{pp_string}",value="This is not a random response.")
await ctx.channel.send(embed=embul)
```
better?
looks good
try using await ctx.reply instead of await ctx.channel.send
still giving the red bar thing
show
in your else block you're still setting color to discord.Color.red()
i did
oh wait
afterwards i did
ok
but still doesnt work
oh you ment the embed color and not a red line as a syntax error🗿
class Verification(discord.ui.View):
def __init__(self):
super().__init__()
@discord.ui.button(label='Verify', style=discord.ButtonStyle.green)
async def callback(self, interaction: discord.Interaction, button: discord.ui.Button):
name = 'Verified'
member = interaction.user
role = interaction.guild.get_role(member.guild.roles, name=name)
await member.add_roles(member, role)
await interaction.response.send_message(embed = discord.Embed(f"Welcome! {interaction.user.name}, you have been granted {role.name} role!", color = discord.Colour.green))
self.value = True
self.stop()```
Does anyone know why it can't find a role
if it's less than something
it should show red
if it above something
it should show green
i wanted it to be like that
try removing the color = None line, it's useless in this case
then why are you setting it to red in both instances
i changed it
LMAOOO
it shows green for 5
but shows red for 6
at what length should it show green or red
size>5:
interesting
so red if more than 5 =s?
green
try flipping that mouth to the side
less than 5 should be red
> to <
wtf
^
its ok, quite common mistake.
i should just go to elementary school 🤡
now the only thing you should change is that lie in the description
again @dusky pine THANK YOU SO MUCH
np
which one?
This is not a random response.
😂
no
it remains ✨
all of my commands has
This is a random response.
but not for this one ;)
How to clone a channel?
!d discord.TextChannel.clone
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to do this.
New in version 1.1.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
async def no_callback(interaction):
await user.send('Offer Declined!')
TCEmbed2 = nextcord.Embed(
title="Offer Declined!",
description=f"{user.mention} `{user}` has declined the offer to join the {emoji}{team.mention}\n > **Coach:** {interaction.user.mention} `{interaction.user}`\n > **Roster:** `{len([member for member in team.members])}/25`"
)
embed.set_author(name="PFG Transactions", icon_url=guildurl)
embed.set_thumbnail(url=emoji.url)
embed.timestamp = datetime.datetime.utcnow()
await TChannel.send(embed=TCEmbed2)
await e.delete()
yes.callback = yes_callback
no.callback = no_callback
u set the callbacks inside the this function, so it doesn't get set at all
outside no_callback
and so send it with ur embed you would do
view = View() # check docs for proper imports
view.add_item(yes)
view.add_item(no)
ctx.send(embed=embed, view=view)
wdym?
{user}
is it @dapper stirrup
or it's just максимка
?
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
thx
sec
str(x) tho
" Represents a Discord user"
will it mention me? or just my nickname
Go ahead and try?
U want name or ping
If u want name just go await ctx.send(ctx.author.name)
🥲 genius
@dapper stirrup
thx, I got it
Thanks @visual island 😂😂😂
da
Hey guys, i got an error that on_reaction_add works only for client.user not other users
There's a code
!d discord.Member
also I have to learn English cause my A -1 isn't good enough
Понимаю
uh
member intents?
did you pass it in your bot class?
bot = commands.Bot(intents=intents)
yeah i was thinking about it right now and when i passed i got a new issue
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
so
go to the developer portal
!intents read what it says about the dev portal
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.
enable the intents that you need
😳 amoled theme on discord desktop is cool
you dont need to do this here xd
wrong channel xD
Is there a downside having a intent enabled that you dont us
yes, discord.py will cache the unwanted objects related to that intents too
for the 2nd part of the question, .all() intents includes previlaged intents too.
if you actually look at discord.py's source state.py -> class ConnectionState:, the cache is nothing but a dictionary which caches objects with id, object key value pairs, which have no limits of how much data they can store. which may tend to be over usage of resources
^
nice spells
meh.
can someone help me idk if it’s to do with discord bht ansi text does not show up on my@iphone it just shows the colour code then the text which looks very ugly is there anyway i can change that but keep the colours?
whatchu say
i do
def format_command_help(self, no, command):
signature = self.helpcommand.get_command_signature(command)
docs = self.helpcommand.get_command_brief(command)
return f"{no}. {signature} - {docs}"```
i dont have a seperate function for get_command_signature
i want to do something like this without having to make a seperate function
```py
def get_command_signature(self, command):
return '**%s%s** `%s`' % (self.clean_prefix, command.qualified_name, command.signature)```
any clue how?
why cant you use get_command_signature
you wanna customize it or
override get_command_signature
lmao, meh as in bored meh 😔
cant
i am doing format_command_help in a different class
hmm
should probably raise an error because its a classmethod
what class does it come from?
bedem = discord.Embed(name="unmute", description=f"{member.mention} has successfully been unmuted!", color=0xBFFF00)
TypeError: Embed.__init__() got an unexpected keyword argument 'name'```
any ideas ?
im trying to make a daily command with sqlite3 and if someone is claiming first time and the date is not found, the date should be recorded included the daily reward because i added 'none' but i keep getting the nonetype error
its title
?
!d discord.Embed 🤡
title? since when tf
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
always have been, thats what the discord payload takes.
nah ... i always used name=
could you show some code.
heres the error:
if str(claimed[0]) == 'None':
TypeError: 'NoneType' object is not subscriptable
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: 'NoneType' object is not subscriptable```
probably sure you did that for the set_author
idk
claimed variable is None here, may i see how is it defined.
heres the partial code:
claimed=db.execute(f"SELECT claimed_date FROM bankData WHERE user_id = {ctx.user.id}").fetchone()
if str(claimed[0]) == None:
#give coins for first time claimers
elif (date.today() - date.fromisoformat(str(claimed[0]))).days > 0:
#give coins to people already in the db
else:
#already claimed. wait for tomorrow```
i need to create a discord bot for my own server, that can perform a certain task by taking information from my own website. I'll give a simple example....like you go onto my website and enter your discord ID and the bot automatically DM's you "hello" [considering u're already in my server as well]. Is this functionality even possible?
can you check your database as well, what IDE/editor are you using?
yes, its indeed possible. im not sure about how you would do that with the website, but the stuff you';re looking for needs nothing more than making a post request to discord
( you can do that without discord.py )
can u explain what u mean by making a post request to discord?
are you aware how http requests work?
no
im pretty new to everything
in python too i just know basics like loops and lists, etc
im using notepad++ and python IDLE for now bcoz vsc is not opening in my pc for some odd reason
imagine installing notepad++ when you got notepad
a post request can be vaguely and generally explained as sending data through one computer to another for further procession
it just doesnt have the functionality
wait u can run code from notepad++? i thought it was just syntax highlighting
okay but how does that relate to the query i asked?
python program.txt in the terminal, ease
yes u need to install the required plug-ins and notepad++ can execute your programs, i suggest checking out a youtube video for it
dosent like notepad only open the code in text format? in its raw encoding?
oh
how did you even assume I read your query lmao
oh 😆
im using notepad++ for now to edit the py files bcoz vsc in my pc is not working
thats not running from notepad, they are two different things. Notepad is a place where you edit code whereas something like VSC is an IDE where u can edit/run/debug/etc
it opens for 1 minute then crashes
sed...
i use python IDLE
hmm not the best ide ig...
still, just use sublime
right click and open with notepad works too...
eval(input ())💀
Uhh, might wanna take it to an OT channel
okay
whats wrong
nothing wrong just don't like using it
what alternative do u use then?
its dangerous, you are basically evaluating python expressions, so i can write stuff you damage your files and it will run that
for inputing list?
i just use normal input most of the time when i need like raw input from terminal then parse the string
i see
if you want to take a list as input, you can use json.loads or input().split() depending on the type of input
ah, then dont worry about it. you will learn it when you have to.
can you suggest me any resource when i can start learning discord bot programming from scratch
yes thats the level im learning at
you need to know python first
u should start with async functions but well since u are still doing basics i would suggest u to not jump so high
if you don't know oop, async-programming etc, even the best resources will not be of any help
ok then suggest me resrouces for learning that then 😆
basically im at school level python [basics, loops, fucntions, lists, etc] and i wanna work my way upto making my own discord bot that serves the purpose i mentioned
!resources , check this out as well https://automatetheboringstuff.com
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
its quite unusual to see someone not jumping in head first to the deep end lol

quite a few people i met in help channels jumped into tkinter/pygame without basics
and like facial recignition lmao
opencv💀
super mario
idk if classes are a must at first, but would be good to learn
yeah

nice i used to play on Nintendo wii
i prob need to get a wii u at some point
nice 😊
that is real # of members?
pretty impressive
lol theres a discord bot tutorial on realpython
https://realpython.com/how-to-make-a-discord-bot-python/
nice
watching 15925 members is pretty sus
is there a less sketch way to say it
*my bot has 15... members in its cache
if they have member intents, yes
i have a bot with 3-4k users in its mutual servers but only 20 of them are cached caused i disabled the member intent
help me pls
@tree.command(name = 'ping', description='veja o meu ping')
async def ping(interaction : discord.Interaction):
embedVar = discord.Embed(title="Ping", description=f"Meu ping : {client.latency} ms")
await interaction.response.send_message(embed=embedVar)
what obj is the client
ok
property latency```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
bruh
okay try client.latency()
i dunno why it isn't working
also try print(type(client))
Try this
await ctx.send(f'Pong! In {round(client.latency * 1000)}ms')
error
ctx don't work
oh you are using interaction
that's why i put it in embed
yes
embedVar = discord.Embed(title="Ping", description=f"Meu ping : {round(client.latency * 1000)} ms")
error
discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: TypeError: unsupported operand type(s) for *: 'property' and 'int'
Can i see your client variable?
yes
class client(discord.Client):
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync()
self.synced = True
await self.change_presence(status=discord.Status.dnd, activity=discord.Game('Meu dev : Francisco Araújo#4576'))
print(f"Entramos como {self.user}.")
aclient = client()
tree = app_commands.CommandTree(aclient)
Why don't you use commands.Bot ?
@ tree.commands
because my bot works with slash commands
client.latency()*1000
bruh
discord.app_commands.errors.CommandInvokeError: Command 'ping' raised an exception: TypeError: 'property' object is not callable
bruh
dude, you said you were using Bot, not Client
I was wrong sorry
but latency is supposed to return a string
is a lib bug?
it returns a float
?
.
aclient.latency
learn OOP
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
Can someone help
doesn't matter, latency exists for both of them
@commands.command()
async def roast(self, ctx, user: discord.Member):
r = requests.get("https://insult.mattbas.org/api/insult")
json_data = json.loads(r.text)
roast = json_data[0]
await ctx.send(roast)```
How can I call the insult if it has nothing to call it by using requests?
requests is sync use aiohttp
oh alright
u can just send the res.text
that don't work
y?
Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\llVll\Desktop\Projects\TMG Bot .git\cogs\utils.py", line 143, in roast
roast = json.loads(r.text)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
await ctx.send(res.text)
do discord bots count as web applications
i wouldn't say so
they are more like api users or in same way like a client of sorts to the discord api/server
web applications are things which provides web services or network services discord bot only performs in discord so it prolly dosent qualify as web applications
Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.description: Must be 4096 or fewer in length.```
How to show embed description that can come like i want to show the things that come in 4096 length
And like x emojis more?
Like this?
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
No error comes up in the console but when i type one of these words nothing happens the code is
``@client.event
async def on_mesage(msg):
if msg.author != client.user:
for text in bad_stuff:
if "Bypass" not in str(msg.author.roles) and text in str(msg.content.lower()):
await msg.delete()``
hey anyone have idea how to design my inventory database
like how do i store user, items user have and all that in database
how many tables i will need
what datatype to store stuff
thanks
Relational?
hmm what are those?
i don't have much experience with databases
Are you using a relational database or NoSQL?
i know foregin keys and all
sqlite3 as prototype
yep
The first thing I can think of is a table with 3 columns: some unique ID, a user ID, and a singular item
The user IDs will repeat
One row is for each item the user has
So when you select that users ID, you get all of their items
well my approach was
i will create two tables 1 for user and 1 for items
now i will give some unique id to items
user table will have user_id as primary key and a items string
And the 2nd table is a mapping of item IDs to items?
items string will look like 1,6,9,10,123
Ah I see where you’re getting it
so i can fetch the user and split the items
That’s a viable strategy
then convert them into int and fetch the item
But usually I like to not mix a bunch of data in one column
i was just trying to save some rows
In a database it really shouldn’t matter
oh
make sense, then i will go for your approach
Yeah you can also do joins in this case
Use the item ID in users table as a foreign key
yes i will
Join the users and items table
thanks :D
@sick birch but as i will need one user table for other kind of info like wallet and all
should i create a table inventory to store inventory of all users
Yes keep your tables scoped properly
and connect user_id with user table (foregin key)
and item_id with item table (foregin key)
That sounds good if you need the other data
If you only need inventory data just join users and items table
oh cool thanks 🙂
.
0
you can calculate it
like loop through roles and add there length to a varable
when variable leangth exceed
break the loop and add footer with "total - looped roles left!"
@setup.command()
@commands.has_permissions(manage_guild = True)
async def channel(ctx, channel:discord.TextChannel):
async with selfbot.db.cursor() as cursor:
await cursor.execute("SELECT channel FROM starSetup WHERE guild =?", (ctx.guild.id,))
channelDATA = await cursor.fetchone()
if channelDATA :
channelDATA = channelDATA[0]
if channelDATA == channel.id:
return await ctx.send("That channel is already setup!")
await cursor.execute("UPDATE starSetup SET channel = ? WHERE guild = ?", (channel.id, ctx.guild.id))
await ctx.send(f"{channel.mention} is now a starboard channel!")
else:
await cursor.execute("INESERT INTO starSetup VALUES (?,?,?)", (5, channel.id, ctx.guild.id,))
await ctx.send(f"{channel.mention} is now a starboard channel!")
await selfbot.db.commit()
``` Error :- `Callback for setup command is missing "ctx" parameter.`
check your setup command
@commands.group()
async def setup(ctx):
if ctx.invoked_subcommand is none:
return await ctx.send("That subcommand does not exist!")
there is ctx
you're missing self
😭 alr
you're in a cog, which goes inside a class, which requires 'self' as its first parameter
yups done now idk how i missed it
i Didn't understand

code py if ctx.invoked_subcommand is none: return await ctx.send("That subcommand does not exist!")
error ```py
if ctx.invoked_subcommand is none:
NameError: name 'none' is not defined
@lyric apex
its None not none
!e ```py
roles = ['cool', 'pro', 'dame', 'epic', 'amazing']
maxLength = 10
length = 0
idx = 0
for role in roles:
if length < maxLength:
length += len(role)
#other stuff
print(str(role), end=", ")
idx += 1
print(f"{len(roles) - idx} more roles")
@chrome latch :white_check_mark: Your eval job has completed with return code 0.
cool, pro, dame, 2 more roles
changed yet same error
isinstance(ctx.invoked_subcommand, None)
try this instead of ctx.invoked_subcommand == None
@commands.group()
async def setup(self, ctx):
if ctx.invoked_subcommand is None:
return await ctx.send("That subcommand does not exist!")
this is the code though
traceback?
yes
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 1342, 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: NameError: name 'none' is not defined
There is really no need for all this over-head, you could just do member.roles[:10] showing only ten roles, etc
!e ```py
max_length: int = 10
roles = [i for i in range(100)]
print(roles[:max_length])
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
above that it should say The above exception was the direct cause of the following exception:. That's the part you want to look at, not the CommandInvokeError exception
Then afterwards, join and append "more roles" etc
it was not the question 😄
The question was to make the roles fit in the embed without going past the limit no?
Or am I wrong\
yes i was showing how to calculate exact amout of roles
like if there are role with only 1 char each
then you can fit more then 10 tho
its says this now :-
Ignoring exception in command setup channel:
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 "/home/runner/new-server/starboard.py", line 22, in channel
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
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 1348, in invoke
await ctx.invoked_subcommand.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: AttributeError: 'Bot' object has no attribute 'db'
you're not setting a bot var named 'db'
um wdym ?
I'm guessing you're using bot vars? and apparently you're trying to access one before you specify it
im just trying to write smh in sql data base
by following a video...by glowstick on starboard
well you gotta assign your db thingamajig to bot.db
setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))``` ??
how ?
same way you'd define any other variable self.bot.db = ...
you just gotta make sure you do that before you start calling any methods of it
@commands.Cog.listener()
async def on_ready():
self.bot.db = starboard.db
setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))
await asyncio.sleep(2)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS starsetup (starlimit INTEGER, channel INTEGER, guild INTEGER)")
await self.bot.db.commit()
``` like this ?
you don't have to use setattr, and yes
alr tyy
on a side note, you generally don't want to do stuff in on_ready
oo okok
it still says the same
do u mind joining the replit ?
what exactly is bot? are you trying to use self.bot?
async with bot.db.cursor() as cursor:
self.bot cause cogs
but you're not using self there, and you're not defining bot anywhere else
It could still be made easier though, for an example ```py
[roles[i] for i in range(len(roles)) if sum(map(len, roles[:i])) < max_length]
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready():
self.bot.db = starboard.db
setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))
await asyncio.sleep(2)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS starsetup (starlimit INTEGER, channel INTEGER, guild INTEGER)")
await self.bot.db.commit()
^^ ??
no
!e ```py
roles = ["abc", "efg", "hij", "lmn"]
max_length = 10
print("".join([roles[i] for i in range(len(roles)) if sum(map(len, roles[:i])) < max_length]))
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
abcefghijlmn
lol if there is a kid who is asking word starting with p what you will tell plate or Pneumonoultramicroscopicsilicovolcanoconiosis
look at the 4th line of your on_ready function, in your async context manager
your code is write but as he is a beginner i was giving code which self explains
setattr(self.bot, "db", await aiosqlite.connect('starboard.db'))``` ? 👀
2 more lines below
bot.cursor...
there ya go
precisely
alr
Ignoring exception in command setup channel:
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 "/home/runner/new-server/starboard.py", line 23, in channel
async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
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 1348, in invoke
await ctx.invoked_subcommand.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: AttributeError: 'Bot' object has no attribute 'db'
ive literally changed it all to self.bot.db
did you remove the setattr?
no what do i write when i remove it ??
i remove the whole line of setattr ?
yeah
i removed it and now it says starboard.db not loaded
anyone?
that's not an error, it's just telling you that you never use took in your code
as in the cog?
yes
do you still have that piece of code in an on_ready event?
how to add cooldown on event like on_reaction_add
you can't add cooldowns to events
Add sleep on it.
@fading marlin can u help me to block multiple ticket in my code
because i dont have any idea how can i block it
use buttons instead of reactions
@bot.event async def on_reaction_add(reaction, user): if '**🚀 ┇ SUPPORT**\n\n ► If you have any question\n ► If you need any help\n ► Open ticket with reaction on this message\n\n ╭ Spamming in ticket is disabled\n ┊ Ghost ping in ticket is disabled\n ┊ Multiple tickets are not allowed\n ╰ Opening for no reason is disabled' in reaction.message.embeds[0].description and reaction.emoji == '👾' and not user.bot: role = discord.utils.get(user.guild.roles, name="@everyone") chan = await user.guild.create_text_channel(name=f'ticket - {user}') await chan.set_permissions(role, send_messages=False, read_messages=False, add_reactions=False, embed_links=False, attach_files=False, read_message_history=False, external_emojis=False) await chan.set_permissions(user, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True) embed = discord.Embed(description="**🚀 ┇ SUPPORT**\n\n ► Thanks for open ticket\n ► Now wait for a response from owners") embed.set_footer(text="† Creator Matija#4633 † ") msg = await chan.send(embed=embed)
how are you loading your cog?
How can i block the multiple ticket of the same name
save the id of the user that reacted to the message, and then check if the ID is on the list of users where you're storing tickets
can u help me to make it ?
if u have time
Wdym ? I use def load when and using a bot command rn for loading
no, sorry
then your on_ready is probably not being called
File "/root/trinity/a.py", line 101
if 'SUPPORT\n\nTo create a ticket react with ������' in reaction.message.embeds[0].description and reaction.emoji == '������' and not user.bot:
^^
SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xed in position 0: invalid continuation byte
u can help?
������ is probably what's causing your issue
but its reaction like 👾
?
LEE
hi?
yo
hey
I don't know what causes this error on windows the script works but when I want to run it on rasberry pi this error pops up
is amazon web services or google cloud better to host a discord bot on
what is users?
there's no "bank" key for him inside of users
make sure to give that key when the member joins your server
help?
you have to import it
oh so i just add import before it?
import discord
from discord.ext import commands
make sure you've got these 2
Oh thx no error message comes up now but theres something wrong with my code when o try activate it nothing happens and theirs no error
its a purge commands btw
@client.command(aliases=['purge']) async def clear(ctx, amount=11): amount = amount+1 if amount > 101: await ctx.send('Cant delete more then 100 messages') else: await ctx.channel.purge(limit=amount) await ctx.send('Cleared Messages')
u have intents enabled?
and intents= discord.Intents.all()
json data with key user id has no key named bank
somehow the bot is stuck on a loop of removing the LIVE role. can someone verify this please?
If you remove a role, it triggers the event, which removes a role, triggers event again, you get the point
did u just jump headfirst into discord bots without knowing basic python?
In short, its like recursion
or a while loop...
Or that, yea
damn, lol
json stores just like a dict so u can make a key the same way as u would in a dict
alright, a bit of revision, would this be good
Nice
hi, hi, I just got a small problem, what's the right name for the permission "manage server"?
I wrote it like this:
@commands.has_permissions(manage_server=True)
manage_guild
Oh, alright, I should've known that, ty
what was the command to install a git library with pip
pip install git+U or something
pip install git+https://github.com/Rapptz/discord.py
ok
does the DiscordUtils package still work to this day (https://github.com/toxicrecker/DiscordUtils)
so just outdated
Yes
welp, alternatively I can just always make my own pagination utils embedded within my own bot file
TypeError: timeout() got some positional-only arguments passed as keyword arguments: 'until'
anyone has a clue y this is happening?
What
u did until=time instead of time
does this provide a better way of handling the role?
@bot.event
async def on_member_update(before, after):
print("Zeddy bot is checking for roles")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if LIVE_ROLE_ID in after._roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if LIVE_ROLE_ID in after._roles:
print("Removing LIVE Role")
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
wym the parameter name isnt until?
I would also check the before
TypeError: timeout() got an unexpected keyword argument 'time'
Because say something else changed (e.g they got a new role. and their activity hasn't changed), it's going to put you into a loop again
there is no such argument
Check if before they don't have an activity, but they have it after, instead of just checking if they have it after
that way you don't lock yourself into a loop
hmm yeah the bot just removed my role again
this is complex.. im kinda lost lmao
Yeah the logic is a bit complex, think it out first before writing out your code
Might be helpful to come up with psuedocode first
TypeError: timeout() got some positional-only arguments passed as keyword arguments: 'until'```
its still happening
so if the bot finds the activity called streaming, check if he has the live role, if he has, just return, else (if he does not and he his streaming) give him the role... if the person isnt streaming, and does not have the role, then return (just do nothing cause it's fine) if he is not streaming, and he has the role, remove the role
@bot.event
async def on_member_update(before, after):
print("Zeddy bot is checking for roles")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if LIVE_ROLE_ID in after._roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if LIVE_ROLE_ID not in after._roles:
return
if LIVE_ROLE_ID in after._roles:
print("Removing LIVE Role")
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
nope he still does not give me the role when im live.. and if i manually give myself the role, HE REMOVES IT!!
lol
Why using _roles, it is a protected member, there's normal roles attribute
And yeah you need to get the role object by ID and then check if it is in list eg
live_role = after.guild.get_role(LIVE_ROLE_ID)
if live_role in after.roles:
...```
ok let me try to fix it
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
live_role = after.guild.get_role(LIVE_ROLE_ID)
print("Zeddy bot is checking for roles")
if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
if live_role in after.roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
else:
if live_role not in after.roles:
return
if live_role in after.roles:
print("Removing LIVE Role")
await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
Seems ok but you have duplicated code when giving and removing roles like you already have live_role why get it again
Also your any is wrong
It must be like this
any(a.type == discord.ActivityType.streaming for a in after.activities)```
Cause it checks if any of conditions from the given sequence is True
So basically you gotta form a sequence of bool values
no way, it's perfect
Sorry wrong place
duplicate code?
i fixed the any()
after.guild.get_role(LIVE_ROLE_ID) in add_roles and remove_roles can be replaced with live_role as you have already defined it
Big floppa is hot 🥵
ye
Hey is it possible for a modal, to have the Server invite of the Current server as placeholder? Nextcord
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
live_role = after.guild.get_role(LIVE_ROLE_ID)
print("Zeddy bot is checking for roles")
if any(a.type == discord.ActivityType.streaming for a in after.activities):
if live_role in after.roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(live_role)
else:
if live_role not in after.roles:
return
if live_role in after.roles:
print("Removing LIVE Role")
await after.remove_roles(live_role)
alright, i got what you mean. i had trouble with the bot removing roles and not giving them too
Yes just parse what invite you would like to have to subclass init
thank you for that info!
So does it work now?
testing now
Ok
i got my print (checking for roles) but it did not give me the LIVE role
Try printing after.activities
it's removing the role also, if i try to give it manually
If they are empty
- If you have dpy 2.0 you need to listen for different event, iirc it is
on_presence_update - Make sure you have presence intent enabled
Because this event is called not only when the activities are updated, roles are included
i think im on 1.8 or something, cause i used pip install
all() includes all intents, you don't need to intents.members = True just an advice
@round knoll what was your result
ok, removed the intents = true
tried to give myself the live role
i dont get the checking for roles
I need you to print(after.activities) and you clearly haven't done that
Do that at the very top of event
Is there a way to get timeout action from the guild audit logs
Mhm lemme check
There is member_update but i really dont know lmao
!d discord.Guild.audit_logs
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.
You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
Yes it is that
got another one
(<Activity type=<ActivityType.playing: 0> name='Terraria' url=None details=None application_id=356943499456937984 session_id=None emoji=None>, <Spotify title='Trapped in Memories' artist='StreamBeats by Harris Heller' track_id='3tsEqC1nDukjBqlrVkC3RE'>)
Zeddy bot is checking for roles
Ok and what happens when you go streaming
im live nothing happening
Does it get displayed in activities list
!d disnake.AuditLogAction.member_update
again if i give myself the LIVE role, the bot removes it
"Triggers in the following situations: ... They were timed out"
Because bot receives on_member_update and finds out you have no activity with type streaming, so it removes the given role
You may avoid that thing by adding a condition that would check if activities exclusively were updated
why is pip stuck on 1.7?
ah
why is there no list of "activities"
https://discordpy.readthedocs.io/en/stable/api.html?highlight=member activities#discord.Member.activities
i tried this, and im getting (<Streaming name='prime and destroyer down.. Terraria shenanigans and deaths.. but mostly deaths || [!hello][!subgoals][!deaths][!cmd]'>
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
print(after.activities)
live_role = after.guild.get_role(LIVE_ROLE_ID)
print("Zeddy bot is checking for roles")
if any(a.type == discord.Streaming for a in after.activities):
if live_role in after.roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(live_role)
else:
if live_role not in after.roles:
return
if live_role in after.roles:
print("Removing LIVE Role")
await after.remove_roles(live_role)
the user has no activity to show then
it says streaming, and the next lines after that are activitytype.playing
Possible to change bots pfp with code?
Yes
!d discord.ClientUser.edit
await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object "(in Python v3.10)") is given through the use of `fp.read()`.
The only image formats supported for uploading is JPEG and PNG.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
bot.user returns an instance of ClientUser
can someone help me fix this please, discord.py is stuck on 1.7 cause i used pip install
# checks if discord activity is streaming, if true, assign LIVE role, if False, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
print(after.activities)
live_role = after.guild.get_role(LIVE_ROLE_ID)
print("Zeddy bot is checking for roles")
if discord.Streaming in after.activities:
if live_role in after.roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(live_role)
else:
if live_role not in after.roles:
return
if live_role in after.roles:
print("Removing LIVE Role")
await after.remove_roles(live_role)
What are the rules on asking for help with hosting bots lol
I'm writing some code for a friend, but idk what service to recommend to her to host the bot
Cause I sure ain't hosting it
not sure if their is any but you would ask here #965291480992321536
i am trying to create a text channel where the ctx member can edit the permissions this is my code
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False , manage_channels=True),
member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
}
channelnamelow=channelname.lower()
channel = await guild.create_text_channel(channelnamelow, overwrites=overwrites , category=category )
channel = await guild.create_voice_channel(channelnamelow, overwrites=overwrites , category=category)
what am i doing wrong ?
so basicly i can do !create test and it will create a text and voice chat called test
but i also want to be able to edit the permissions or invite other people in how do i do that
for now i am trying to be able to edit permissions of those channels
Well, a voice channel doesn't have read message permission so you can't give them to that member, maybe try creating overwrites for each voice and text channel?
allright ill try that
btw u should use manage_channel instead of manage_channels
let me try that
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: no permission called manage_channel
thats what it says
hmm
let me tell my goal basicly i want to do !create test and it will create a text and voice channel in a catagory where members can invite other members
with !invite @ membername
but the invite thing didnt work at all
so i am now trying to make it so that people can add members by editing the channel permissions
but its still not working 😂
Maybe this can help you out : https://discordpy.readthedocs.io/en/stable/api.html?highlight=overwrite#permissions
i tried that i copied over the permissions from there but still no luck :/
alright the bot looks fixed now.. that was annoying lol
spi.sniped_messages= {}
@spi.event
async def on_message_delete(message):
spi.sniped_messages[message.guild.id] = (message.content,message.author,message.channel.name,message.created_at)
@spi.command()
async def snipe(ctx):
contents,author,channel_name,time= spi.sniped_messages[ctx.guild.id]
channel = ctx.channel
try:
embed=discord.Embed(description=contents, color=discord.Color.green(),timestamp=time)
embed.set_author(name=f"{author.name}#{author.discriminator}",icon_url=author.avatar_url)
embed.set_footer(text=(f"Deleted in: #{channel_name}"))
await ctx.channel.send(embed=embed)
except:
embud=discord.Embed(title="Snipe not found",color=discord.Color.red())
embud.add_field(name="There's nothing to snipe!",value="L")
await ctx.channel.send(embed=embud)
``` the except part doesnt work help
heres the fixed (for now?) code
# checks if discord activity is streaming, if true, assign LIVE role, if False, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
live_role = after.guild.get_role(LIVE_ROLE_ID)
print("Zeddy bot is checking for roles")
if any(a.type == discord.ActivityType.streaming for a in after.activities):
if live_role in after.roles:
return
else:
print("Giving LIVE Role")
await after.add_roles(live_role)
else:
if live_role not in after.roles:
return
if live_role in after.roles:
print("Removing LIVE Role")
await after.remove_roles(live_role)
maybe, but trying to make the code cleaner is what broke it in the first place
why does it say that ;-;
isinstance(i, discord.ActivityType.streaming) will never be True because i is an instance of discord.Activity and discord.ActivityType is an enum
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
not a screenshot
The issue is probably not in that line or you have some "phantom spaces" somewhere
Also why use replit 😳
mobile ;-;
You do know that you still have to now reset ur token
i did
Cool
Hello. please help me
your code is alive
and why error
What error?
My bot, worked for 2 days without any problems.
And now he going offline
when i click (Run)
Well, you're gonna need to scroll up a bit in console there. All thats shown there is some html, nothing useful.
seems like a cloudfare ban
yeah was about to say that
you would need to kill your container
the IP your replit was running on probably got blocked 💀
and where is better?
because the IP your bot uses when running off of replit is shared. With who knows how many other people, who may also be running discord bots. If one of those bots gets api banned or the IP gets blocked by cloudflare, then yours gets blocked as well. Usually a dedicated VPS is the way to go for hosting a bot
i have hosting
Reset your token, you've leaked it
uptimerobot and better uptime
Uptimerobot is not a host
It's a monitoring tool to see if your websites stay up
better uptime is similar
Check the pinned messages, personally I prefer AWS EC2 instances or a raspberry pi
and what is best hosting site?
do you have no money
There really is no "best" hosting site, take a look at a few of these
#discord-bots message
bruh i just use sparked host
this is free?
You're never going to find a free (and reliable) hosting or VPS service. And if it is free, there is always some kind of catch.
There is no single "best", though it's usually a good bet to settle with large cloud service providers (amazon, google, microsoft, digitalocean, oracle, etc)
me when hosting my first bot using a leftover server from my workplace
Shouldn't be difficult, just make an on_voice_state_update event I believe the name is
Find the channel using the after voice state, join that
should be very easy
does background task block main code?
my task all are asynchronous btw, but always get the application doesnt responds when the background task running
anyone know some js
with open("emails.txt", "r") as file:
lines = file.readlines()
chosen_index = random.randrange(0, len(lines))
chosen_line = lines[chosen_index]
with open("emails.txt", "w") as file:
del lines[chosen_index]
file.writelines(lines)
return chosen_line
line = pop_random_line2()
pyautogui.typewrite(line)```
how do make that work?
Yes, though it's a python server so we can't provide help with that here
what's inside the task?
ive tried this code, and it doesn't write the text from the txt
That's out of scope for this channel, you may have better luck claiming a help channel for more personalized help
oh mb lmao, im just a discord bot dev and i posted in wrong channel
.topic exists here i didnt know
Suggest more topics here!
and it's customized for this channel
proper grammar
and please stop capitalizing embed titles like
Are You Sure?
Are you sure? looks better
Hey guys, I'm trying to run my bot script on my raspberry pi but I think I messed up some of the packages or something
If anyone can help, that would be great! please ping me
Hey I finished reworking my tutorial for interaction bots using Wumpy. I think there's some regulars here who might have something to say? Feedback is encouraged, even on stuff like the theme (although I know that it isn't perfect; I am trying
) and screenshots!
https://wumpy.readthedocs.io/ (if on mobile, open with Desktop mode)
Requested desktop version on brave mobile client, formatting issue still persists
Same
Both in portait and landscape mode
Reader mode works nicely though 😄
I haven't really specialized it for mobile yet. It should be readable if you set it as Desktop site?
Wow, I am sorry. That's... surprising behavior
Actually, relatively the mobile version is much more appeasing then what the desktop version renders currently
Kek
Oh never mind, I scrolled over and everything broke
Yeah umm.. ignore the table of contents, you can't see it anyways 🙈
Ah shit I really need to work on the mobile stuff. Getting things together has been somewhat painfully and I imagine it doesn't get better 😅
And you're sure none of them is blocking?
It doesn't matter if the function is async
Nothing inside of it needs to be blocking
Well actually to be more precise, nothing that takes a relatively long time should be blocking
i think nope
can you send the code for the task
hmm
Because if nothing inside is blocking then something else is wrong
@tasks.loop(seconds=150)
async def r_task(type):
urlist = RADB().webhook_url(type)
for i in ecchilist:
embed = await RedditAuto().redditembed(i)
if len(embed) >0:
async with aiohttp.ClientSession() as session:
embeds = embed["embeds"]
ids = embed["ids"]
for i in embeds:
for url in urlist:
webhook = Webhook.from_url(url, session=session)
await webhook.send(embed=i)
await RADB().addsended(ids[0])
ids.pop(0)```
def webhook_url(self, type):
urls = []
for i in self.RedditAutomationDB.find({type:"true"}):
urls.append(i[f"{type}_url"])
return urls```
yeah, blocking mongodb driver
ok so i need to change async mongo
!pip motor :> or use run_in_executor
i think thats the problem but when i search "is mongodb threadsafe" it shown yes
ill use motor
ggs
thx for ur help
newbie 🙂
pymongo?
yeah they were using that ig
ic
for i in self.RedditAutomationDB.find({type:"true"})``` based on this
ye its pymongo
i have my cs exams in 2hrs aaaaa
yeah i saw the reddit was a bit misleading
GLHF lol
bruh u will ace it
the reddit is arl async
yeah, the reddit part is async, you're using asyncpraw right?
its just some mysql, stacks and network system shit afterall
uh is there any motor docs?
indeed, just google for "motor readthedocs"
i dont understand from that docs lol
eh wait
so its just collabin motor and pymongo?
its quite similar to pymongo tho~
ok...
MySQL the only confusing part is multiple joins doubt they will go that deep into joins tho
ok lol im just reading false docs
there's nothing like that in 12th syllabus
basic queries ( select, insert, update, create table, alter table), string operations ( sum, max , etc... ) Group by, and some constraints
tbh they dont even ask for constraints in exams, they just give you some tables and ask you to peform search/write operations on them
constraints which the checks and parameter for creating tables right?
do they give foreign keys would slightly interesting if they did that 👀
yep, CHECK, NOT NULL , etc
yes they do
nice
intresting part is if u use foreign key in same line as column name SQL parses but doesn't enforce
so u have to do
foreign key Id references tablea(id)
ATB sarth ace it 🎉
thanks, ill go study now
i need to revise the networks and communication chapter, too much theory to learn
Good luck, I keep forgetting the damn full form of ARPANET
ARPANET lol
the first internet on the world
hey i have like 2 buttons with some condition the issue is that when 2 ppl click on the buttons together it runs the last check part 2 times
code:
https://paste.pythondiscord.com/ifuvorebip
the who_win function did 2 times
class Split(nextcord.ui.Button):
def __init___(self):
super().__init__(label="Split", style=nextcord.ButtonStyle.blurple, custom_id="Split_P2")
async def callback(self, interaction):
return # random shit here
class SplitOrSteal(nextcord.ui.View):
def __init__(self, ctx, player: nextcord.Member, opponent: nextcord.Member):
self.player = player
self.opponent = opponent
self._ctx = ctx
self.player_choice: str = None
self.opponent_choice: str = None
self.player_clicked = False
self.opponent_clicked = False
super().__init__(timeout=180)
@nextcord.ui.button(
label="Split",
style=nextcord.ButtonStyle.green,
custom_id="Split_P1"
)
async def _callback(self, button, interaction):
if interaction.user == self.opponent:
return await interaction.response.send_message('This is not your turn!', ephemral=True)
if interaction.user != self.player:
return await interaction.response.send_message('This is not your game!', ephemral=True)
for x in self.children:
self.remove_item(x)
item = Split()
self.add_item(item=item)
self.player_choice = "Split"
self.player_clicked = True
await interaction.response.edit_message(content='{self.player} has choosen, its {self.opponent}\'s turn.', view=self)
Then make it run so that only the user who initiated the command can only make the buttons works @slate swan
it sends some HTTPException, label is required
I have passed label for Split button
why does it say so :hmm:
that 1 view is for 2 users.
Oh then make sure that whoever presses the button it’s there turn
Or just wait for one user at a time
Cool 😎 I think it would be better for your code that way or wateve ur making
Trying to add a role twice does not remove the role, right?
No?
Why would u do that anyways
Iterating through a list of members who "applied" for the role didn't get it.
Ah makes sense then why not add a check in it
So for eg
Members = []
for m in Members: If m.user.role == role.id: Something Else: Something
I didn't think it would be of any use apart from making the code a bit slower but then I remembered reading something in the docs where running the same thing twice basically inverts the values. I think it was actually in discord.py and for app_settings.
Never heard of that but u could be write , and I don’t think adding that check will slow down to ur code at all
It’s processes at fast speed so u don’t rly need to worry bout that
But the list is thousands of members long lol. Like you have to retrieve the channel history first and then retrieve the member info and then add role in them if they exist, Anyway, the process is done now. Thanks for your time!
Ye makes no difference
Trust me , I have something like that that iterates through 10of thousand of user id, and isn’t slow but it’s rly up 2 u
Just make sure your code is neat
Or just remove users from that list who already have the role
What’s the issue?
Try if role.name is not in team:
Are you checking the users role?
Whos role u checking if it’s in that list?
I can’t rly help since I don’t rly know the attributes that nextcord use
But if I’m not mistaken from what u said , just get a list of the author role and then check if in the team
If that’s not what u mean , ur code doesn’t make sense to what u said
Oof I got to go to schoool rn , hope it makes sense or if I couldn’t help then I’m sorry @slate swan
if role.name not in teams
from discord.ext import commands
bot = commands.AutoShardedBot(command_prefix='!')
@bot.event
async def on_voice_state_update(member, before, after):
if not before.channel and after.channel and member.id == 974780999936397352:
await member.voice.channel.connect() # Connect to the channel```
pip install PyNaCl
better to do discord.py[voice] since version issues
Yes
The channel do be kinda inactive today since no questions being asked
Don't worry, I'm back
Oh F***
I need to find a way to reprogram the proximity sensor of my phone
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: I/O operation on closed file
any idea what might be causing this.
Code?
you're trying to read/write to a file that you closed earlier with file.close()
the problem is that the command isnt even getting invoked, so i dont think the problem is with that ?
uh, i can't help if you won't send any code.
Command did get invoked
yeah, i am sending the code, i was just letting you know that, that wasnt the case
"Command raised an exception"
you are right yes\
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.
Can you like give only that command's code
Like I am not going to scroll through all that
just read the comments on there
pretty out in the open
else
@bot.slash_command(guild_ids=config.Guild, description="Report a bug.")
async def bug_report(ctx):
async def Dropdown_callback(interaction):
value = Dropdown.values[0]
embed = Embed(
title=f"You selected {value} bug.",
color=Colour.blue()
)
await Original_Interaction.edit_original_message(embed=embed, view=None)
modal = Feedback(Value=value)
await interaction.response.send_modal(modal)
Dropdown.callback = Dropdown_callback
view = View(Dropdown)
Original_Interaction = await ctx.response.send_message(view=view, ephemeral=True)
I don't think this is what causing that error
Also you should really look at PEP 8
!pep 8
maybe the get_img_module from Misc.SubModule_Image_Fetcher is causing the problem.
looks like a func that deals with files
And yeah I also recommend splitting your code into several modules
Having everything in one file is a very bad idea
oh wait
Hello everybody and welcome back to another episode of "Developing a discord bot in d.py without knowing python"
and subclass the views for god's sake
is that for me ?
Nope don't worry, it's just a meme here
Seems rude
The truth is rude
Unnecessary autoremove remove 😳
i'll be out then, better figure it myself rather than asking for help here.
We could help you if you would send the block of code where your error raises
Main Function
@bot.slash_command(guild_ids=config.Guild, description="Check Equipment Information.")
async def equipment_info(ctx):
# Making Views/Options
First_menu_view = discord.ui.View()
Second_menu_view = discord.ui.View()
Third_menu_view = discord.ui.View()
# Making Screen 1 buttons.
button1 = Button(label="Army", custom_id="Army",
style=discord.ButtonStyle.green)
button2 = Button(label="Navy", custom_id="Navy",
style=discord.ButtonStyle.green)
button3 = Button(label="Air", custom_id="Air",
style=discord.ButtonStyle.green)
button4 = Button(label="General", custom_id="General",
style=discord.ButtonStyle.green)
# Making Screen 2 buttons.
button5 = Button(label="Gold Equipments", custom_id="Gold",
style=discord.ButtonStyle.green)
button6 = Button(label="Purple Equipments",
custom_id="Purple", style=discord.ButtonStyle.green)
button7 = Button(label="Blue Equipments", custom_id="Blue",
style=discord.ButtonStyle.green)
button8 = Button(label="Green Equipments", custom_id="Green",
style=discord.ButtonStyle.green)
button9 = Button(label="Grey Equipments", custom_id="Grey",
style=discord.ButtonStyle.green)
back_to_first_button = Button(label="<- Back")
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.
Nice, the whole code 
send both full code as well as the main func. Whatever you prefer
sent*
views
Could be easily simplified with for loop + array
dictionary*
Tuple of tuples is ok too ig
mhhh first of all you should not name variables Type or any other python builtin functions/methods
Yeah that is what would happen
buttons_data = (("Button1", "custom_id1"), ("Button2", "custom_id2")) # actually you need the custom ids only if you have persistent views
for name, custom_id in buttons_data:
view.add_item(Button(label=name, custom_id=custom_id, style=discord.ButtonStyle.green))```
Dict might look cleaner tho I agree
and a View subclass would be better in case
Totally
I'm gonna eat ramen flex
i am just learning so, I did find view subclass and stuff but didnt want to jump into it right away.

And went with the method that seems easier by the first look but in fact is generally bad
Yeah : P
Tbh their examples for callbacks that have the purpose of setting a value and then returning it are not really good too. They could actually make something like I made, the get_result of the view will just return the pressed button's return_value without having to declare callback for each button https://github.com/Exenifix/AIAS/blob/78b9f2590fe5044a851b729dabb4f9f044f1c38e/utils/views.py#L32-L76
Yeah, fixed that
but anything on I/O error ?
Let me fix the whole thing and i will be back.
Ok
Send the full traceback when you're done
file I/O
if the file is already closed, you cant perform any actions to it, these are the cases
file = open("uwu.txt")
file.read()
file.close()
file.write("uwu") #This raises the same error as the file being closed
''' or '''
with open("uwu.txt") as file:
file.read()
file.write("uwu") #This raises the same te error as the file being closed```
sarth otw to correct me
in short, you need to perform all those operations inside the context manager itself
nu lmao
its not about reading/writing like this. I use context managers. old code is above, writing new rn
what's the benefit for GitHub student pack with jetBrains?
you get all their IDEs' professional versions for free
so after linking my git acc to jetBrains site i just download the professional ide?
Can someone explain?
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
😔 sigh ic
the module hadnt been installed as of the time when the script was run
indeed, and login to the ide with your github
oh no
thx for helping🎉
U also get access to Fleet 👀
does the old pycharm get auto uninstall or do i have to do it manually?
exploring one by one
A new IDE which should be better than VSC or any other IDE
you can have all the 3 ( or 3idk( distros at once
how did CS go sarth 👀
Ah, yes
really good, it was easier than expected
i saw the paper u said no joins 👀
set 4 didnt have too many network questions thankfully
yeah
bliss
most answers were in the questions itself
😔 idk our teacher didnt teach us but yeah i learned NATURAL JOINS
lmao i learned them all except i have a bit of trouble with multiple joins
i got the same set, sql is a life saver 
so it's fine to have pycharm community and pro at same time?
my friend got set-4 too
i think everyone did
prolly yeah
but when i go to venv/Lib/site-packages there is nextcord so why does it say no module named nextcord?
i mean i saw there was two questions barely tricky one was group by and natural join one asked output and other the statement
do you change the source of your terminal or wherever you run the file from to your venv?
linter prob ig...
linter wont raise an error on runtime
oh runtime didn't see
i dont know what you mean with that
when u run a file normally it will show in terminal running from file path blah blah venv stuff
are u running the correct venv?
yes i should be
Virtual Environments
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using Windows PowerShell, you may need to change the execution policy first. This is only required once:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
are plugins and themes free too?
im not sure, but with professional maybe yeah
it says no valid license associated
☝️
ic u have to req license
for plugins?
no u have to req for education license in and apply for it in jet brains website
not really. lets shift to an ot channel and talk about it.
ok
I am just gonna send this again because I imagine there's different people online right now. I have reworked my Tutorial a bit for interactions bot with my library. If you have the time, check it out and let me know what you think!
The docs don't render nicely on mobile, use desktop if possible: https://wumpy.readthedocs.io/
really looks great, but i think that it would be a bit more cleaner if the Topic header would be seperated from the contents, like here if it would be like
Tutorial
Getting Set Up
Creating Commands
...
that may look cleaner
as for the actual content, the implementation is very clean, especially the Option constructor
looks nice but it would looks a bit better if these index
Tutorial
Getting Set Up
Creating Commands
Command Options
Option Choices
Context menus
were a bit more spaced and slightly bigger
Thank you both! I fully agree, I need to add some indentation and spacing. The other pages should be indented underneath Tutorial
np glad to be of help🙂
hey guys
I know I can use ssh to run code on my raspberry pi
but I can't close the powershell window, or else the script will end, right?
How would I run my code on the raspberry pi 24/7? Also, would I have to hook it back up to a monitor if I wanted to rerun the script?
Is there any way run the code on the raspberry pi using ssh, rather than running the script on the powershell on my PC?
please @ if you respond lol
hi im sending a view with a msg so how do i get the msg object in that view
msg = await ctx.send(...,view=someview())
i want msg in the view
view = discord.ui.View()
view.message = await send(..., view = view)
``` you can now access the message from the view using view.message / self.view inside the view class.
There's option choices for that. No idea how to define it in different libraries
a = rps(self.bot,firstperson=firstperson,firstpersonscore=firstpersonscore,secondperson=secondperson,secondpersonscore=secondpersonscore,match=match+1,toatalmatches=toatalmatches,ctx=interaction)
s = disnake.Embed(title=f"{firstperson.name}'s chance",description=f"Match {match+1}/{toatalmatches}",color=aqua)
a.msg = await interaction.send(f"{firstperson.mention},{secondperson.mention}",embed=s,view=a)
#view parame
(self ,bot: commands.Bot,firstperson : disnake.Member , firstpersonscore : int,secondperson : disnake.Member , secondpersonscore : int, match : int,toatalmatches : int,ctx : commands.Context, msg = None)
am i doing something wrong ?
it print None when i print it ...
if that a slash command?
yes, thats not how it works
..
then?
!d disnake.Interaction.edit_original_message use this :V
await edit_original_message(content=..., *, embed=..., embeds=..., file=..., files=..., attachments=..., view=..., components=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original, previously sent interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://docs.disnake.dev/en/latest/api.html#disnake.InteractionMessage.edit "disnake.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
Note
If the original message has embeds with images that were created from local files (using the `file` parameter with [`Embed.set_image()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_image "disnake.Embed.set_image") or [`Embed.set_thumbnail()`](https://docs.disnake.dev/en/latest/api.html#disnake.Embed.set_thumbnail "disnake.Embed.set_thumbnail")), those images will be removed if the message’s attachments are edited in any way (i.e. by setting `file`/`files`/`attachments`, or adding an embed with local files).