#discord-bots
1 messages · Page 1057 of 1
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
don't leak your token ofc
yep i hid the env file lol
I hope .env
lol it was .env
heres the bin for wb.py
https://paste.pythondiscord.com/azegapafiw
you seem lost
i am lost
you're just throwing a custom_guilds everywhere to try and make it work
yeah 😦 i is dumb boi
try and implement this simple implementation, scrap the "subclassing a bot" thing for now
should i remove everything i tried throwing it on first?
correct
ok ill try that first
Hello
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
import cogs.whiskey
from colorama import Fore
load_dotenv()
bot = commands.Bot(command_prefix="$")
bot.custom_guild_ids = os.getenv('GUILDS')
```like this?
that's right!
and how can i fix my events cog. ill paste it in here and you can tell me whats not needed
import disnake
from disnake.ext import commands
from colorama import Fore
from datetime import datetime
import time
#below are two date time functions that have different functions but one of them adds to the other durring startup
from wb import guild_ids
start_time = datetime.now()
mytime = time.localtime()
if mytime.tm_hour < 12:
timeofday = 'AM'
else:
timeofday = 'PM'
class events(commands.Cog):
"""Useful Features for Bot Development."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
def setup(bot):
bot.add_cog(events(bot))
that's all fine
you can access the variable from wherever in that cog now via
self.bot.custom_guild_ids
hrmm
C:\Users\Andy\virenv\Scripts\python.exe C:/Users/Andy/PycharmProjects/WhiskeyBotMain/wb.py
Traceback (most recent call last):
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
from disnake.ext import commands
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
from .bot import *
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
class Bot(BotBase, InteractionBotBase, disnake.Client):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
@guilds.setter
NameError: name 'guilds' is not defined
Process finished with exit code 1
i still dont know what i broke UwU
no idea at this point, maybe ask in the disnake discord server, I'm using discord py
Hi, I have a very newbish question I'm sure.
This is my first time working with python I have extremely small prior experience with coding and I just want to create a command that translates text to French and I cant seem to manage it I have been trying multiple things but if someone could help me out that would be awesome!
you should first learn how to use a Translate API outside of discord py
no?
yes, this is a project wrapped around a project
you can just use a dict
should i try making a copy of this code and just pulling the repo again to see if i just broke something by changing something wrong in my code?
I'm using googletrans
can't say, sorry
That would be a massive dictionary
yup
Why do hard work when something already exists for that?
its really not allot of work
excuse me?
To translate a language to another is a lot of work
cant you just do it letter by letter?
translating every single word in a dict, as well as sentences? that's huge
No??
he's talking about translating languages
Also not all languages use an alphabet
french to english etc
they use their own no?
oh no translation is a bit more complex than that
No, take for an example mandarin, there is no alphabet. There are only predefined characters
Some languages kill the brain, some have like 18 alphabet letters, some have none etc
And it's not as simple as doing A (lang 1) -> A(lang 2)
Better to just use google's api
🤷♂️
There are other things at play, such as english vs french. French assigns gender to words, where as english does not
I am using googles api
sure, does that already work for you OUTSIDE of a command?
like with a given input or whatever
Nah, Im going to look into it more and comeback if I don't find anything. Thanks for helping me readjust how to look at the problem though
always make sure to do it outside the bigger project first, then adapt where needed
the module got corrupted apparently and it works now
Great
did i mess that up
import disnake
from disnake.ext import commands
from colorama import Fore
from datetime import datetime
import time
#below are two date time functions that have different functions but one of them adds to the other durring startup
start_time = datetime.now()
mytime = time.localtime()
if mytime.tm_hour < 12:
timeofday = 'AM'
else:
timeofday = 'PM'
class events(commands.Cog):
"""Useful Features for Bot Development."""
def __init__(self, bot: commands.Bot):
self.bot = bot
print('Loading Events cog')
@commands.Cog.listener()
async def on_ready(self):
print(Fore.GREEN + 'Connected!')
print('Bot is ready!' + Fore.WHITE)
print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
embed = disnake.Embed()
embed.title = f"**Online**"
embed.set_footer(text="Logging System")
embed.set_author(name='WhiskeyBot', icon_url=f"{self.bot.user.avatar}")
embed.description = f"""**Bot Startup and Information**
Start Time: `{datetime.now().strftime('%b-%d-%Y at %I:%M:%S')} {timeofday}`
Current Uptime: <t:{round(datetime.timestamp(start_time))}:R>
Bot account: `{self.bot.user.name}`
Bot ID: `{self.bot.user.id}`
Guilds: `{len(self.bot.guilds):,}`
Users: `{len(list(self.bot.get_all_members()))}`
Disnake Version: `{disnake.__version__}`
Loaded Cogs: `{list(self.bot.cogs)}`
Developer: `whiskeythefox#7339`
"""
GUILD_ID = 798726719573065749
CHANNEL_ID = 798726720181633047
location = self.bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
await location.send(embed=embed)
ids = self.bot.custom_guild_ids
@commands.slash_command(name="uptime", guild_ids=ids)
async def uptime(self, ctx):
As mentioned like 3 hours ago, you don’t want to do any shit in on_ready
I’m gonna go to sleep, ☮ⓅⒺⒶⒸⒺ☮
uhh where do i set the ids to self.bot.custom_guild_ids then lol
There’s no need for you to do that
It’s already defined…
You can already access it via self.bot.custom_guild_ids
so just put guild_ids=self.bot.custom_guild_ids in the commands args?
for the slash command as shown above?
Stop thinking you have to redefine that stupid guild_ids in every file
You did it once, you can use it anywhere without having to redefine it
ok but i got the error
Traceback (most recent call last):
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 49, in <module>
bot.load_extension('cogs.events')
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 487, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 419, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: NameError: name 'self' is not defined
when i tried
@commands.slash_command(name="uptime", guild_ids=self.bot.custom_guild_ids)
async def uptime(self, ctx):
Hmm, I’ve never used your library, I can’t tell you how to pass it to the cog
Not the slash commands
that's not the issue here.
You’ll probably have to load the custom guild ids on top of the file and access it that way
mhm
or just import your config variable
just make sure you load it
before you access it
Yup, so there was never any need for the botvar after all
... how would i do that lol
wdym, it's just like importing any other variable
Loadenv in every file
hmm how would i load the env if its in the folder about the current folder
are you using python-dotenv?
No, don't load the env in every file lol
just make a variable that you import into all of your other cog files
you can just make that variable in I assume you have a bot.py file
or use the botvar
please give an example to help my brain that is bouncing like the dvd logo
why would you need to access the env variables in a function header?
this is there code...
that's why
makes perfect sense
why not just set the global test_guilds variable instead
no don't do that
globals should be avoided as much as possible and this is a case that they can be avoided in.
alright so you have a bot.py file yes?
that's where you are loading extensionsand initializing your bot
doesn't matter what it's called
ok
yes
yes ik
but most people call it a bot.py file
so that's why I was asking...
alright so in that file you should load your config and set it as a variable in that wb.py file
make sense so far?
the variable can just be called config
doesn't really matter whatever you want it to be
hmm so config = os.getenv('GUILDS')?
I have no idea what your env file looks like
so however you were loading it before just do that
just don't set it as a bot variable
well you can still set it as both because I am assuming you access the config outside of function decorators as well.
TOKEN = "Nope UwU"
GUILDS = 798726719573065749```
yeah
wait should the guilds be [the number]
so just do what you were doing before?
what about it?
well is that what you meant to do lol
meant by what?
Yes, but don't do it bc it's against TOS
and we won't help/show you how.
this
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
you are making a variable called config in python
thats why
and then are setting it to your environment var
ah ok
because using it for bots is allowed but user accounts not allowed
because bots are meant to use the api but the user accounds use what discord says they should use
bc account automation is a thing.
any sort of account automation that's not authorized through discord's own public api through a bot user is not allowed.
yeah since they arent marked as bots
well you can do it but we cant help you. and it is all at your own risk of getting your account terminated
ok so now i have
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
import cogs.whiskey
from colorama import Fore
load_dotenv()
config = os.getenv('GUILDS')
bot = commands.Bot(command_prefix="$")
now how am i passing it to cogs? @pallid meadow
You just import config in your cogs
From .wb import config
Or whatever your import would be
Ok I will put that in when im back on my system in a bit. I'll let you know if there is issues
from dotenv import load_dotenv
load_dotenv()
custom_guild_ids = os.getenv('GUILDS')```
put this in your main file
thats in my main file
and then import that variable in your cog file
from <main file> import custom_guild_ids
hmm? should i make a config cog?
hell no
lol i saw the correction right after the message i sent
just import that variable from your main file to your cog file, then it's also accessible there
normally, you'd just use a botvar for this (so you don't have to import it all the time), but since you can't use self.bot in your slash command decorator, you'll have to import this
I hope you finally understand after doing this for the past 5 hours
that's what relative imports are, you should google that
python relative import
They already have that…
Please make sure you actually read all their code before giving help
he called his guilds variable in the .env a config..
and i have became confuzzled. how am i going to import from the dir above lol
you'll have to do as said
cause i tried .wb and ..wb and they didnt work
you should first understand what this does before implementing it
and when i tried ..wb i got
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ImportError: attempted relative import beyond top-level package```
you can also google errors yk 😉
yeah but when i googled it i was still confused
what did you google?
great!
!paste
well you are trying to import a top level package from your dir.
So you are in your main and doing from ..?? import ??
i got this error https://paste.pythondiscord.com/akuhecebol
You can't import relatively above the current dir
he's in a subfolder cog
and needs to import the main bot file
@cloud dawn
you should start reading the errors
there are simple fixes
Yeah so? Then it's still in the main.
ah, you were referring to "which file to import"
It's just from then no .. needed
You always imoport "relatively" to main
@....slash_command(..., guild_ids = config)
now you can finally get some well deserved sleep
omg i feel so dumb about that lmao. but now i have to fix the env part of guilds
so would they be GUILDS = [number]?
i have GUILDS = [798726719573065749] whats wrong in it
nothing
because it throws the errror
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: ValueError: guild_ids must be a sequence of int.
can you print type(config)?
maybe that's the issue
can i do int(os.getenv('GUILDS'))
no pls
hi , umm i am new to programing i can someone tell me where i can make discord bots?
omg thx
alright, I found a possible solution for you
https://stackoverflow.com/a/53599459
so your env will look like
GUILDS = 55151,515151,515151
then your
GUILDS_STRING = getenv shit
config = [int(guild_id) for guild_id in GUILDS_STRING.split(",")]
gl, hf!
thanks ^w^
wait why were you saying not to use anything in on_ready
cause i have an embed that needs to send on bot settup
because that event can get called multiple times, it doesn't really only get called "on_ready"
oh is there a reccomendation for it to just run when the bot starts?
the top 5? for the main?
cause i was kinda wanting to put it in a cog so it dosent clog my main file
you can just keep the print in on_ready, remove the rest
yup, top 5
ok
where do_stuff_here() is replaced by all the shit you wanted in the on_ready
umm can i move the start script to my cog?
ok. i was using that cog for just that and a uptime command
ok
should use map
I use a .json for my config, so idk what to suggest there tbh
um... its not running any of it now
show me the code in your main ofc
!e ```py
print(*map(int, ["1", "2", "3"]))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
1 2 3
@slate swan i gotchu
💓
new link pls
huh. thats the link for the code
oh add .py to the end
you never added line 5
line 5? the commented line?
bruh
i have that out lmao since i didnt need it
not in your code, in this code ofc
https://gist.github.com/cyrus01337/5595cde67d4925f3f92bfa9dbfc0d754
time to get some sleep for you bud
time to get some rest
i will after im done dropping errors out of my code lol
yup, the Baguette makes it 100% accurate
it is prefixed with a Hon hon hon (stereo typical french laugh) and suffixed with baguette
I noticed
im convincing an old friend of mine from france to come back to online gaming and I want the discord server to make him laugh
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
import time
# import aiohttp
# import aiofiles
# import logging
# logging.basicConfig(level=logging.INFO)
start_time = datetime.now()
Traceback (most recent call last):
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 15, in <module>
start_time = datetime.now()
AttributeError: module 'datetime' has no attribute 'now'
from datetime import datetime
original
He would also be able to code all of this blindfolded
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 31, in <module>
ct = datetime.datetime.now()
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
never told you to change that
I told you to change the import 🧠
yep apparently i had an old typo that didnt trip earlier for some reason
thanks lol
ima go to sleep now
peace
Guys how to fix it
i am programming a bot in discord and i want to know how i can make it so that when someone does a specific command, it chooses a random image from a set selection of images
how can i do that?
(i am new to python btw)
random.choice()
You can use the random module and have a list of image links and randomly choose from that list and send the chosen image link
He won't know what to do with that unless you explain it
so what would that code looks like
would i just link the image files and make a array or images?
does python even have arrays?
idk javascript is all i know rn
It doesn't
is this duck , the dude that helped me with the selenium problem ????
aight
I don't know selenium
dang it
duck lmao
Numpy has arrays
i wanted to hire him for something
idk what numphy is lmfao
!pypi numpy
btw hi skev
Hello
Link the image files?
What i do is that i send the images first here in discord and copy the discord image link
Then just send those links
To not have images in my system
Wdym it can't choose anymore
I mean
You could do this but it feels like a hacky ass way
!e ```py
import random
ree = [1,2,3]
print(ree.pop((ree.index(random.choice(ree)))))
print(ree)
@supple thorn :white_check_mark: Your eval job has completed with return code 0.
001 | 2
002 | [1, 3]
It gets the randomly chosen item in the list and also removes it from the list
So that it can't chose that item anymore
this is my code
so where would i set that up?
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result
anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with
this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality
to manage commands...
im confused
As it says it's a subclass of discord.Client so it can do anything discord.Client does and more
sorry, im not very well versed in python
so how would i implement it?
any specific spot?
sorry
Rather than using names use the id of the role
Then just get the role using that id
Literally just tell him to replace it
Nothing more and nothing less.
team1 = ctx.guild.get_role(teams.pop(teams.index(random.choice(teams))))
!b
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
There's going to be more than that bruv
at the top of your file, import the commands extension
from discord.ext import commands
where you define client replace it with
bot = commands.Bot()
There’s a significant difference between these two, one may be a subclass. However, that subclass in your case will be what handles your commands and what makes you make them easier.
!e ```
while 1000:
print("o")
@obtuse heron :x: Your eval job has completed with return code 143 (SIGTERM).
001 | o
002 | o
003 | o
004 | o
005 | o
006 | o
007 | o
008 | o
009 | o
010 | o
011 | o
... (truncated - too many lines)
Full output: too long to upload
@true quartz
I'd have to explain to him to use commands rather than manually doing every prefix commands like some caveman
thanks
#bot-commands
there’s actually a guide somewhere on how to use the commands framework.
Idk where it is but you could probably find it on the repos examples folder
A tutorial to help you make better Discord bots.
does this tutorial cover what im tryna do?
Probably not but it's a good discord bot tutorial
then ill use it in the future
Covers disnake.
Also what you're trying to do is easy
And nextcord only.
Disnake good
but i just want help with what im trying to do in simplest terms
i have no clue what im doing
I’m pretty sure he’s using dpy.
is discord_slash not a module?
Why would you use that
idk, i was taking code off a github repo
The commands framework between all 3 libraries carry significant changes and different implementations between the three
So I don’t think giving him that guide is wise.
Unless, he wants to swap to disnake. Which is more hassle than he probably wants to have.
Do what the error says.
Back
Pass in a prefix to invoke your bots commands with.
?
i have no clue what that means
I'm doing my homework 💀
its fine
@sage otter can you explain how to do it in the simpliest of terms please lmfao i dont know anything about python
add command_prefix="!"
Inside commands.bot()
inside the ()?
Ye
damn the syntax told you what to do
Then for now is discourage you from trying discord bots. A significant amount of knowledge is recommended before attempting discord.py
Discord.py isn’t a beginner library.
it seems most people are now using replit
I learned python from it ¯\_(ツ)_/¯
cool.
that's not something to be sorry about, i am still a learner
alright
@true quartz did u add what I just said
idk where to add it
Brooo
sorry
inside the ()?
ye
Tf
idk
Remove that add bro wtf
It wasn't
Don’t apologize either. Just because you don’t know something. We all start somewhere. Like I said, you should try learning the language or versing yourself in it a little more before attempting. Familiarize yourself with the terms so you're not always confused.
You're doing this to yourself.
bot
You should of stopped when he said "I don’t know anything about python"
well i dont really know where to start with learning it
Change all @ name to bot instead of client
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Don't use client as ur bot instance ⚠️
yeah, you defined your commands.Bot(...) object as bot, dunno where you got client from
Corey Schafer has a good beginner playlist
Check it out
it's also suggested that you don't use the on_message event to handle commands. Use the built-in decorators like @bot.command to do that.
I don’t know anything about python
Sad
oh
You should of known why as soon as he said that.
that makes sense
You should just stop now. Trying to help an absolute beginner who probably just learned Hello World with an advanced topic like dpy will do more harm than good
i know more than that
Now I'll create a maths dc bot to make maths easier for discord users
That's a lowercase b
Damn few days ago I got same and I didn't even realize that it's bot and I stop cuz everything was fine 😂
^ @true quartz
thanks
take a look at the documentation/repository for examples
Please and thank you.
should i have support for both prefixed commands & slash commands?
i remember reading somewhere that discord wanted ppl to just migrate to slash commands
is your bot in 100 guilds
Just because they encourage you doesn’t mean you should.
if it's <75 then you can still use normal commands
otherwise you should migrate to slash commands
i mean if you get the message intent you don’t have to
ok i can use normal commands
but should i have support for both
that's you to you
k cool
you can use the hybrid command deco to support both at the same time
oh ppl still use the normal discord.py here? thought that library was dead or something
you can read about it here
https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6
yeah I wouldn't suggest using py-cord
big f
tried testing it with a prod bot and it was just filled with internal errors lmao
although it was a valiant effort from the lib developers
Am using on_member_remove how to know if the user left on his own or was kicked?
k wait
@commands.command()
@commands.has_permissions(ban_members=True)
async def heist(self, ctx, ping, amount, sponsor, mins: int):
time1 = datetime.now() + timedelta(minutes=mins)
await ctx.channel.purge(limit=1)
await ctx.send(f"{ping} :money: **Heist Starting!** :money:")
hEmbed = discord.Embed(title=f"⏣ {amount}", description=f" :flexUwU: Sponsor: {sponsor} \n:flexUwU: Timer: <t:{time1.timestamp():.0f}:R> \n Requirements: \n \n:dot:Grab **Heist Ping** role to get ponged! \n:dot:Withdraw coins: `pls withdraw 2000` \n:dot:Use a life saver.", color = discord.Colour.random())
hEmbed.set_footer(text=f"Thank the grinders too")
msg = await ctx.send(embed = hEmbed)
reaction = await msg.add_reaction(":DI_heist:")
users = [users.mention async for user in reaction.users()]
await asyncio.sleep(mins)
await msg.edit_message(content=f"{ctx.author.mention} It is heist time!, may the heist commence")
@client.command()
async def tt(ctx):
with open("dice.gif", "r") as f:
image = discord.File(f)
await ctx.send(file=image)``` ```py
Traceback (most recent call last):
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnicodeDecodeError: 'charmap' codec can't decode byte 0x8f in position 250: character maps to <undefined>``` What am I doing wrong here?
Just pass the file name to discord.File
is anyone running here premium membership model for any bot? need some idea how to make one 🧐 thinking for using strpie
Stripe would probably be the best
Obviously a database with premium users
And a check for premium only commands
Hardest part would be stripe integration
I think patron has an API that’ll make it pretty easy to process premium purchasing as well
import discord
from os import listdir
from discord.ext import commands
class Bot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", case_insensitive=True, intents=discord.Intents.default())
async def cogs_manager(self,bot: commands.Bot, mode: str, cogs: list[str]) -> None:
for cog in cogs:
try:
if mode == "unload":
await bot.unload_extension(cog)
elif mode == "load":
await bot.load_extension(cog)
elif mode == "reload":
await bot.reload_extension(cog)
else:
raise ValueError("Invalid mode.")
except Exception as e:
raise e
async def on_ready(self):
print(f"Logged as: {self.user} | discord.py{discord.__version__}\nGuilds: {len(self.guilds)} Users: {len(self.users)}")
print("_"*100)
async def close(self):
await super().close()
print("Shutting down...")
async def startup(self):
"""Sync application commands"""
await self.wait_until_ready()
await self.tree.sync()
async def setup_hook(self):
"""Initialize the db, prefixes & cogs."""
# Cogs loader
cogs = [f"Cogs.{filename[:-3]}" for filename in listdir("./Cogs") if filename.endswith(".py")]
print(await self.cogs_manager(self, "load", cogs))
# Sync application commands & show logging informations
self.loop.create_task(self.startup())
if __name__ == '__main__':
bot = Bot()
bot.run(token)
I have this basic code
but I can't run any commands
from my cogs
MY cog:
import discord
import discord.ext.commands as commands
class H(commands.Cog):
def __init__(self, bot):
self.bot = bot
async def cog_load(self):
print("H cog loaded")
@commands.command()
async def ping(self, ctx):
await ctx.send("Pong!")
async def setup(bot):
await bot.add_cog(H(bot))
why would your cogs_manager need a bot arg? no need for that
Are you sure your cog is being loaded?
Does your whole listdir thing actually find the cog files?
also
Sync application commands & show logging informations
self.loop.create_task(self.startup())
why don't you justawait self.startup()?
lastly
print(await self.cogs_manager(self, "load", cogs))
printing this makes no sense, since it doesn't return anything
there are other small optimizations, but these just are the most obvious ones
also, you probably noticed that the on_ready prints no guilds nor users (or the incorrect length) since the cache isn't loaded there yet => you don't want to do anything in on_ready except maybe a print
!changed
and finally, to top things off:
cogs = [f"Cogs.{filename[:-3]}" for filename in listdir("./Cogs") if filename.endswith(".py")]
verify that this isn't just an empty list, which could be why your cogs aren't loaded
it is not empty
returns ['Cogs.H']
class Bot(commands.Bot):
def __init__(self):
super().__init__(command_prefix="!", case_insensitive=True, intents=discord.Intents.default())
async def on_ready(self):
print(f"Logged as: {self.user} | discord.py{discord.__version__}\nGuilds: {len(self.guilds)}")
print("_"*100)
async def close(self):
await super().close()
print("Shutting down...")
async def startup(self):
"""Sync application commands"""
await self.wait_until_ready()
await self.tree.sync()
async def setup_hook(self):
"""Initialize the db, prefixes & cogs."""
# Cogs loader
cogs = [f"Cogs.{filename[:-3]}" for filename in listdir("./Cogs") if filename.endswith(".py")]
print(cogs)
#load cogs
for cog in cogs:
await self.load_extension(cog)
# Sync application commands & show logging informations
self.loop.create_task(self.startup())
great, then that should be it I'd say
is this better
try and see
.
how can i send help for a particular cog
cog name: utilitycmds
user used: ,help cog utilitycmds
sends help for that particular cog
default help command
I am getting:
send() got an unexpected keyword argument 'ephemeral'
For:
await channel.send(embed = choose_catagory_embed, ephemeral = True, view = view)
You can only send ephemeral messages on interaction respond
thats wrong, you need to do ```py
reaction = await (await ctx.chanel.fetch_message(message.id)).reactions
and how can i mention em?
all users in the list?
same code i sent earlier
you reaction variable was wrong that's it
anyone know how i can make sure my bot auto restarts upon any crashes?
reply to it
channel*
not sure if i should ask this here
but why did rapptz quit discord.py at first
i get the part about staff being nonreceptive to feedback & stuff
but i don't really get the part about "gateway intents" or "privileged intents"
if anyone could explain that to me, i'd be really grateful
You mean the blue text?
If yes:
[link text here](url here)
I don’t think the work in footer
its not necessary
!d discord.Embed.url is also there in case u wanna make the title, clickable
The URL of the embed.
This can be set during initialisation.
In the error handler
Guys my bot was working fine before 5 minutes but when i am using comamnds now its not working even it's online and there's no error
If possible pls help me
I'll dm you file if need
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
send your code ^
Or its replit error?
also in your error handlers, add ```py
else:
raise error
else:
raise error/exc/exception```
guys can someone help me
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.```
anyone got smth for how i can make my bot delete its own messages? (a cleanup command that deletes the bot's past 15 messages or so in the current channel)
get the channel history using discord.Channel.history then u can check the message author
and delete if author is the bot
hey, how would i make a command inside of another command? for example inside of a ! lyrics command i could have song lyrics loaded
ah k will give it a shot ty
Well
You could invoke another command inside that command
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
[`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally...
!d discord.ext.commands.Bot.get_command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list
of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get
the subcommand `bar` of the group command `foo`. If a
subcommand is not found then `None` is returned just as usual...
👀
hey i enabled in my bot to join guilds for me btw i authorized it btw i am not joined to any of the servers, how to configure the bot to make me join server my authorizeing it
I don’t understand what you mean
You want your bot to invite you in the server it joins?
Guys when i say %help my bot send the following result in image /
How can I remove it and make a new help command
there is already a default command named help, but u can remove it
bot = commands.Bot(command_prefix='',help_command = None)
Ok how can I make my own?
yes
Like other comannds?
after u remove it
now u can
u can create a command called help without the error
Hmmm like other comannds?
yes
u dont have to change the command now
+ akai123 hacked ⏣ 696,696,696 out of the bank.
I want to get integers after ⏣ and ignore all ints before it, any idea?
Use regex
Well you could just do this but i think it's bad
int(re.search(r'\d+', m).group())
i was using this but it gets all
!e ```py
duck = "+ akai123 hacked ⏣ 696,696,696 out of the bank."
print(duck.split("⏣"))
@supple thorn :white_check_mark: Your eval job has completed with return code 0.
['+ akai123 hacked ', ' 696,696,696 out of the bank.']
ooo
So the usernames with digits doesn't fuck you
There's probably a better way to do it but all i could think of that's good
why does my uptime robot online hosting via replit not work,
code:
from flask import Flask
from threading import Thread
app = Flask('')
@app.route('/')
def home():
return "I'm alive"
def run():
app.run(host='0.0.0.0',port=8080)
def keep_alive():
t = Thread(target=run)
t.start()
The website given is correctly pasted into uptime robot whats wrong, when i go offline the bot goes offline
ValueError: parameters are of unsupported type guys how do i fix this
use type hinting ig
can i send my code and u check it?
sure
1 sec
but not sure if i can help
because u are not linking the uptimebot to ur bot?
where is the error
It claims to be in the on_message event
So check there .
send the whole error
Kk
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\beta test\bot.py", line 37, in on_message
async with client.db.execute("SELECT levelsys FROM levelSettings WHERE guild = ?",
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\context.py", line 41, in __aenter__
self._obj = await self._coro
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 184, in execute
cursor = await self._execute(self._conn.execute, sql, parameters)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
ValueError: parameters are of unsupported type````
async with client.db.execute("SELECT levelsys FROM levelSettings WHERE guild = ?"
?
this is the error i think
the schema is set to have different data types but the data you input has different types
what shall i do then to fix it?
could you show your database schema and the code where you input data?
async def setup_db():
client.db = await aiosqlite.connect("level.db")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
await client.db.commit()``` this?
hm, and the part where you input data?
idk u have to check my code
thats what im asking for...
i think the second arg in execute is supposed to be an iterable
async with client.db.execute("SELECT levelsys FROM levelSettings WHERE guild = ?",
(guild.id))
try (guild.id, )
^
kk
client.db.execute() as cursor uwu
parens dont make tuple 😔
error in the event
theres no errors
u copied the wrong address
on_message is an event-
i meant ....
oh yea
not the website id
I see
The url you link to uptimerobot should be the flask app url, not your replit project url (you can see the app's url on the upper right panel of the replit page).
it might be to do with indents @slate swan
smh
idk these are the 2 new commands i implemented as a group
he knows it already 👍
@tropic burrow https://replit.com/@MonkeyProgram/discordbot1py?v=1#main.py this is ur repl isnt it lol
og bruh\
👀
can someone see an error in my code?
this part first
remove return
no errors , no commands respond
if i do it affects my code , so i cant
without the new stuff i added theres no issues , so i know for sure its the new code
@slate swan any ideas?
just pass instead of return
What's the issue
sure
like none of 'em?
which command no work? @warped mirage
yeah probs someone is blocking the code without me knowing idk
slvl?
i coded a group , slvl's and in the setupdb and in message event and level command i added some extra stuff so check over there , 0 commands respond
Ouch sql statements
what the
turn on logging
lol
That's alot of sql executions for an on_message
async def setup_db():
client.db = await aiosqlite.connect("level.db")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
await client.db.execute(
"CREATE TABLE IF NOT EXISTS levelSettings (levelsys BOOL, role INTEGER, levelreq INTEGER, guild INTEGER)")
await client.db.commit()``` any errors here?
Won't it be better to have one context manager handle all that instead of creating 3
yea
doesnt seem like it
what the heck is that if statement
this is in the level command
Checks whether it is not empty and its first item is turthy
No, tbh
Weird
Wait @maiden fable I might have an idea , can u check my if statements and ye maybe indents or smth
If not then alright I guess
Can u share the code link again
@slate swan idk if it’s a rule here but generally there shouldn’t be helping with stuff against minecraft stuff or smth idk
Cuz auto bots for a game is technically a cheat
@warped mirage also don't have so many context managers
I’ll fix it after but until then can u check my stuff
Use a single one.
Sometimes these can cause uncaught errors
Can u show the error
Not u
only this?
Wait, can u try doing def handle(ctx, *args):
they are fine until and unless it is distributed illegally, in essence, set out for production without the authorization of the company, Mojang
this comes straight from their TOS though
Try opening a help channel, never used the module sooo
me who was surprised that you're helping with something that has javascript inside python
Well I am using JS for making a project's frontend and since I am looking for ways to use the least amount of JS and use the JS API in Python, sooooo
So any ideas for my code
my trust issues are more severe now
Lmao why
I never really hated JS, but I just prefer using Python wherever I can
Nothing like opene a js file and seeing that
()(function()((()(()()(())))
That just makes you wanna alt f4
Agreed
reasons I hate JS sometimes
And ofc, the CORS policy sucks
istg I spent days trying to fix that error due to which I wasn't even able to send requests to the backend API on another port 🤣
doesnt everyone love minified js
its fun
vc, get out before everyone here loses their mind
you*
CORS is good*
*When you have a deep understanding of CORS
the * doesn't go for me
I still remember messing with React's config file and bothering ppl in the React discord for days
Anyone know how to make a tiktok notification bot using json
Is there a tiktok api?
yes
Does anyone know error to my code
Use the API
There is?
TikTok gives developers the tools they need to connect creators and communities. You can share videos from your app to the entire TikTok community with just a tap. Plus, simple coding lets you embed TikTok videos into any webpage for more diverse ways of sharing.
Where can I find it?
Ashley just posted it
That’s not api
https://paste.pythondiscord.com/hesoyevoyu someone xD
If that is the case, then https://discord.com/api/v9 isn't also an API
@client.command()
async def fight(self, ctx, user:str=None, *, weapon:str=None):
if user is None or user.lower() == ctx.author.mention or user == ctx.author.name.lower() or ctx.guild is not None and ctx.author.nick is not None and user == ctx.author.nick.lower():
await ctx.send("{} fought themself but only ended up in a mental hospital!".format(ctx.author.mention))
return
if weapon is None:
await ctx.send("{0} tried to fight {1} with nothing so {1} beat the breaks off of them!".format(ctx.author.mention, user))
return
await ctx.send("{} used **{}** on **{}** {}".format(ctx.author.mention, weapon, user, random.choice(fight_results).replace("%user%", user).replace("%attacker%", ctx.author.mention)))
There is a error in it
Can anyone help me fix pls
I’ve made a yt notification bot without the YouTube api
Yo did u check my thing or u cba lmao
And works
I did, didn't find any indent issue
Hmm
Well, then its against YT ToS (:
@client.command()
async def fight(self, ctx, user:str=None, *, weapon:str=None):
if user is None or user.lower() == ctx.author.mention or user == ctx.author.name.lower() or ctx.guild is not None and ctx.author.nick is not None and user == ctx.author.nick.lower():
await ctx.send("{} fought themself but only ended up in a mental hospital!".format(ctx.author.mention))
return
if weapon is None:
await ctx.send("{0} tried to fight {1} with nothing so {1} beat the breaks off of them!".format(ctx.author.mention, user))
return
await ctx.send("{} used **{}** on **{}** {}".format(ctx.author.mention, weapon, user, random.choice(fight_results).replace("%user%", user).replace("%attacker%", ctx.author.mention)))
There is a error in it
Can anyone help me fix pls
Getting information from youtube.com without using the API via the means of bot is against their ToS @formal basin
https://paste.pythondiscord.com/hesoyevoyu guys can someone check my code , there’s no errors but no commands respond
WHAT
Please don't spam repost + send the error
Send me link of it saying that
Pls help me
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Btw it’s private
@client.command()
async def fight(self, ctx, user:str=None, *, weapon:str=None):
if user is None or user.lower() == ctx.author.mention or user == ctx.author.name.lower() or ctx.guild is not None and ctx.author.nick is not None and user == ctx.author.nick.lower():
await ctx.send("{} fought themself but only ended up in a mental hospital!".format(ctx.author.mention))
return
if weapon is None:
await ctx.send("{0} tried to fight {1} with nothing so {1} beat the breaks off of them!".format(ctx.author.mention, user))
return
await ctx.send("{} used **{}** on **{}** {}".format(ctx.author.mention, weapon, user, random.choice(fight_results).replace("%user%", user).replace("%attacker%", ctx.author.mention)))
There is a error in it
Can anyone help me fix pls
For the second time please don't spam repost 🗿 and send the error if there is one
I’m not using yt dl
Yeah I don’t think I’m breaking any TOS there
Ytdl is just one
Wdym
I use it in my js bot with Distube I think
Which I’m not using
What do u use
It's just one package 😂
What do you use it for?
Music
The most popular , but any thing that mimics its functionality in any way does break tos
I use ytdl and distube for music I think
So ur saying YouTube will sue me for this and I’m getting arrested?
Anything wrong with this I’m not using yt dl
@stone beacon
can someone tel me with I will get arrested
lmao no
What then
🤣
Tell me what gon happen then
naw not imo
😮💨 phew
But I'm no expert
It’s private bot
No need to get paranoid m8
Bro so what happens then … I’m asking for an answer
00008B dark blue hex code
Nothing is gonna happen to you 💀
If push comes to shove you'll have to stop using the package
Then why do people make it sound like it’s terrifying
hence so many streaming bots died
Oh ok
Good thing I don’t use it
The notion is just that we cannot help anyone here with that cuz then big bad google will try to screw up the server
Breaking the law is infact illegal
!d discord.ButtonStyle.blurple or do you need the hex?
ah wait
If it’s illegal then how the f do u make music bots
Makes no sense , everything is illegal
classmethod blurple()[source]
A factory method that returns a Colour with a value of 0x5865F2.
its 0x5865F2 @slate swan
!d nextcord.Colour.blurple
classmethod blurple()```
A factory method that returns a [`Colour`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Colour "nextcord.Colour") with a value of `0x5865F2`.
anyone know how to make a tiktok notification bot? No api and using json
😔 they use Colour lmao. tho Color is just an alias for the same
Insanity
!d nextcord.Colour.blurple
classmethod blurple()```
A factory method that returns a [`Colour`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Colour "nextcord.Colour") with a value of `0x5865F2`.
If u r using the official YT API, then u r not doing anything wrong
Here is the code I did for the YouTube notification bot I want it to be a tiktok one
!d disnake.Colour.green is same as that color iirc
classmethod green()```
A factory method that returns a [`Colour`](https://docs.disnake.dev/en/latest/api.html#disnake.Colour "disnake.Colour") with a value of `0x2ecc71`.
I’m not using any api
Oh yh this
How do I get the official one
google it and you're 99% sure to find it on the front page
Wut
Lemme say all my packages related to music that I have
You do know that alot of these packages wrap the api's e.g discord.py wraps the discord api
ytdl-core , ffmpeg static, distube , @distube/spotify THESE ARE ALL THE PACKAGES I HAVE . JS
Alright this a bit ot
?
https://paste.pythondiscord.com/hesoyevoyu can someone help me , no commands respond or no errors
Damn sad times
No more music bots
Good thing I don’t use YouTube dl
This is inside on_command_error:
debug_message = f"{ctx.command} invoked by {ctx.message.author} with error. \n {e.__class.__name__}: {e}"
and I am getting this error:
debug_message = f"{ctx.command} invoked by {ctx.message.author} with error. \n {e.__class.__name__}: {e}"
AttributeError: 'CommandNotFound' object has no attribute '_ErrorHandler__class'
Why is that?
I even handle CommandNotFound inside on_command_error
elif isinstance(e, errors.CommandNotFound):
print("Reached notfound")
logger.debug(debug_message)
await self.send_command_suggestion(ctx)
got it
I use ytdl core is that fine?
Idk
ytdl-core , ffmpeg static, distube , @distube/spotify THESE ARE ALL THE PACKAGES I HAVE . JS
Are these fine ?
Tbf the distube is fine cuz it’s spotifies page
spotify doesnt allow unauthorized streaming either
How can we make a music bot if everything is illegal
Either license the music you play correctly or dont make a music bot
Wdym by license it
pay to be able to stream the music to an audience
Do u know how much they charge ?
No idea, but it's not cheap
If you're streaming popular music and you didnt pay for licensing it is illegal
period
ok , what I’m in streaming music that isn’t popular
Ok let me rephrase
Any music on spotify, youtube, amazon music, etc. is - with a 99.999% certainty - copyrighted and cannot be streamed legally without paying for licensing it
Wait general things like suggest commands , ban commands and all that sort are legal right ? Since they are for discord purpose only .
yeah why wouldnt they be
Idk so it’s only when ur using a different app for discord , that’s when it becomes illegal if not paid
Correct ?
https://paste.pythondiscord.com/nudetayumo
Guys i am get a indent error in it
I am not able to know how can I fix it
!paste
Can someone rephrase what this means
@client.command()
async def test(ctx):
await ctx.send("0--- loading")
await asyncio.sleep(1)
await message.edit(content = "-0-- loading")
await asyncio.sleep(1)
await message.edit(content = "--0- loading")
await asyncio.sleep(1)
await message.edit(content = "---0 done!")
Pls help me getting error that
Undefined name 'messsge'
U need to define •message•
How me not understanding
@warped mirage did ctx.edit
Now it says discord.ext have no attribute edit
@slate swan can you help me pls
I used ctx.edit
It says discord.ext have no attribute edit
error says pretty much all
Hmm
where is message defined?
Or i need to add variable
a GuildChannel, Message, etc. have edit methods
ok
not discord
yes
Please tell me what should I do? I'm not a lawyer, and I'm sure I can't spell it correctly.
state the TOS for your application
I figured it out, but how do I do it right?
So that there are no problems in the future
iirc, its asking you to input a url to a website, right?
best you could do is, either create a repo on github and add your bot's TOS to the README.md or create a static website (html and css)
I'm wondering how to write the conditions themselves, the big text itself
How to do it right
dont have to write like a huge pallet of text lol, you could state anything necessary
Got it, I just find a lot of these files
why add a tos to ur own bot
woudnt make too much sense tbf
.........its necessary for every application under production
it states out the rules about how you can use the app and how you cannot
so wtf am i meant to put
TOS for the app
and how do i do that
add the website url to your TOS
ofc after creating the TOS
can u gimme a example of tos
even tho im making my own bot which wont be illegal ....
@slate swan
something like these rules for the usage of an app
can u explain more...
like using the commands ? like what damn tos lol , for who????
hello
tos and licences are different things
tos is terms of service
they are rules for an app for the consumer to the product
for example, take a library, it has a rule that all the visitors are to be silent, visitors here are consumers and the library is the app, and the library's TOS is that everybody be quiet in the hall
hopefully you understand
so how does it work for my bot lmao , its not like im gonna make bad commands
bruh no sense.......
how do I know about your bot....
commandlist ?
you're only forced to add a TOS to your bot if your bot is gonna be undergoing verification
ok so if i add a tos what am i gonna have to add
yes.
how tf do i make rules for commands , gimme a example
as i said before i aint gonna add illegal commands....
think
@slate swan look , i understand this , so what they will have access to my bot and dashboard
or what cuz makes no sense
idfk will they have access to my application? and view token and that
well, no
then how the f do they see this ???
then why the f do i make tos and what for
read this
dude, you're stubborn
only discord have tos for fs lmao
😭
bots cannot have a tos
every application does
a website, an android app, an iOS app
etc

