I found this help command from GitHub and put it in my code. I checked all errors and under those errors was the error that config was not defined. How do I fix it?
Link to GitHub:
https://gist.github.com/nonchris/1c7060a14a9d94e7929aa2ef14c41bc2
Code (it's a long code, I know):
import discord
from discord.ext import commands
from discord.errors import Forbidden
"""This custom help command is a perfect replacement for the default one on any Discord Bot written in Discord.py!
However, you must put "bot.remove_command('help')" in your bot, and the command must be in a cog for it to work.
Original concept by Jared Newsom (AKA Jared M.F.)
[Deleted] https://gist.github.com/StudioMFTechnologies/ad41bfd32b2379ccffe90b0e34128b8b
Rewritten and optimized by github.com/nonchris
https://gist.github.com/nonchris/1c7060a14a9d94e7929aa2ef14c41bc2
You need to set three variables to make that cog run.
Have a look at line 51 to 56
"""
async def send_embed(ctx, embed):
"""
Function that handles the sending of embeds
-> Takes context and embed to send
- tries to send embed in channel
- tries to send normal message when that fails
- tries to send embed private with information abot missing permissions
If this all fails: https://youtu.be/dQw4w9WgXcQ
"""
try:
await ctx.send(embed=embed)
except Forbidden:
try:
await ctx.send("Hey, seems like I can't send embeds. Please check my permissions :)")
except Forbidden:
await ctx.author.send(
f"Hey, seems like I can't send any message in {ctx.channel.name} on {ctx.guild.name}\n"
f"May you inform the server team about this issue? :slight_smile: ", embed=embed)
class Help(commands.Cog):
"""
Sends this help message
"""
def __init__(self, bot):
self.bot = bot
#commands.command()
# #commands.bot_has_permissions(add_reactions=True,embed_links=True)
async def help(self, ctx, *input):
"""Shows all modules of that bot"""
# !SET THOSE VARIABLES TO MAKE THE COG FUNCTIONAL!
prefix = # ENTER YOUR PREFIX - loaded from config, as string or how ever you want!
# setting owner name - if you don't wanna be mentioned remove line 49-60 and adjust help text (line 88)
owner = # ENTER YOU DISCORD-ID
owner_name = # ENTER YOUR USERNAME#1234
# checks if cog parameter was given
# if not: sending all modules and commands not associated with a cog
if not input:
# checks if owner is on this server - used to 'tag' owner
try:
owner = ctx.guild.get_member(config.OWNER).mention
except AttributeError as e:
owner = config.OWNER_NAME
# starting to build embed
emb = discord.Embed(title='Commands and modules', color=discord.Color.blue(),
description=f'Use `{prefix}help <module>` to gain more information about that module '
f':smiley:\n')
# iterating trough cogs, gathering descriptions
cogs_desc = ''
for cog in self.bot.cogs:
cogs_desc += f'`{cog}` {self.bot.cogs[cog].__doc__}\n'
# adding 'list' of cogs to embed
emb.add_field(name='Modules', value=cogs_desc, inline=False)
# integrating trough uncategorized commands
commands_desc = ''
for command in self.bot.walk_commands():
# if cog not in a cog
# listing command if cog name is None and command isn't hidden
if not command.cog_name and not command.hidden:
commands_desc += f'{command.name} - {command.help}\n'
# adding those commands to embed
if commands_desc:
emb.add_field(name='Not belonging to a module', value=commands_desc, inline=False)
# setting information about author
emb.add_field(name="About", value=f"The Bots is developed by Chriѕ#0001, based on discord.py.\n\
This version of it is maintained by {owner}\n\
Please visit https://github.com/nonchris/discord-fury to submit ideas or bugs.")
emb.set_footer(text=f"Bot is running {config.VERSION}")
# block called when one cog-name is given
# trying to find matching cog and it's commands
elif len(input) == 1:
# iterating trough cogs
for cog in self.bot.cogs:
# check if cog is the matching one
if cog.lower() == input[0].lower():
# making title - getting description from doc-string below class
emb = discord.Embed(title=f'{cog} - Commands', description=self.bot.cogs[cog].__doc__,
color=discord.Color.green())
# getting commands from cog
for command in self.bot.get_cog(cog).get_commands():
# if cog is not hidden
if not command.hidden:
emb.add_field(name=f"`{config.PREFIX}{command.name}`", value=command.help, inline=False)
# found cog - breaking loop
break
# if input not found
# yes, for-loops have an else statement, it's called when no 'break' was issued
else:
emb = discord.Embed(title="What's that?!",
description=f"I've never heard from a module called `{input[0]}` before :scream:",
color=discord.Color.orange())
# too many cogs requested - only one at a time allowed
elif len(input) > 1:
emb = discord.Embed(title="That's too much.",
description="Please request only one module at once :sweat_smile:",
color=discord.Color.orange())
else:
emb = discord.Embed(title="It's a magical place.",
description="I don't know how you got here. But I didn't see this coming at all.\n"
"Would you please be so kind to report that issue to me on github?\n"
"https://github.com/nonchris/discord-fury/issues\n"
"Thank you! ~Chris",
color=discord.Color.red())
# sending reply embed using our own function defined above
await send_embed(ctx, emb)
def setup(bot):
bot.add_cog(Help(bot))
A config.py file is a file you use to set configurations to your code easily. On the code you sent, it's used to identify a couple of key attributes.
If the original creator hasn't posted the config.py on the github, you can probably do it yourself. First, you will create a .py fle named config, and then you will write on there the attributes that this code calls using config. For example, in one part of the code, we have this:
except AttributeError as e:
owner = config.OWNER_NAME
That means the code is going after the config file to look for the attribute "OWNER_NAME", so, when you create your config.py file on your own folder, you will have to define this attribute, with something like:
OWNER_NAME = "your name or something"
The same goes for every other attribute called through the config.
After you finish defining all of this, make sure the config.py file goes inside the same folder that your code is located, and put on your code this simple line:
import config
And then your code should run.
Related
I've been building a discord bot with pycord, and so far it's been a very well documented affair. However, when I got to the newer function of Modals, I ran into some trouble. Below is the code for my Modal and the slash command that calls it in the discord server. The modal sends fine and the callback runs fine.
When I try to get the user that filled in the modal, however, I run into trouble.
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Enter your prompt here and click submit.", style = discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction): # DO NOT alter the callback name
embed = discord.Embed(title="Modal Results", color=5763719)
embed.add_field(name="Suggested prompt:", value = self.children[0].value)
print(discord.Interaction.user)
# returns "<member 'user' of 'Interaction' objects>" instead of the user attribute that I expected.
# embed.set_author(name = discord.Interaction.user.name) <- error: 'member_descriptor' object has no attribute 'name'
await interaction.response.send_message(embeds=[embed])
#bot.command(description = "Call forth a test Modal.")
async def trymodal(ctx):
modal = MyModal(title = "Modal via Slash Command")
await ctx.send_modal(modal)
I tried calling on discord.Interaction.user, which, according to the API doc should have the attribute 'name', among other things. When I debug and halt the code right after the print, I can indeed see a local variable 'user' in the object discord.interactions.Interaction.
If I try to address the attribute, I get the error 'member_descriptor' object has no attribute 'name'.
I haven't had formal training (yet), but if I had to guess I'd say it's seeing discord.Interaction.user as a member, and not as the class that it is supposed to be? I read this in the API documentation under the 'user' attribute of the class Interaction: https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction.user
It says Type: Union[User, Member]. I have no clue what that means? I know User and Member are both classes with a lot of overlapping data in them. Does my problem have anything to do with this? Or am I missing a basic class thing?
Bottom line: how can I access the attributes that I know User has?
You're accessing the wrong thing.
discord.Interaction.user is getting the user property on the Interaction class. Your interaction variable is called interaction - you need to access the user attribute on that variable.
async def callback(self, interaction: discord.Interaction):
print(interaction.user)
discord.Interaction is the Object type and is a Class. You even use it as a type hint for the variable in the function definition. Just make sure to access the variable attributes.
I'm attempting to use the python Twitch-Python library for a simple Twitch bot to connect to chat and respond to messages. The bot works as expected, but about 1/6 times the bot fails to connect and the program simply ends. As explained on this error page, it seems to be because the thread ends and doesn't return anything at all https://github.com/PetterKraabol/Twitch-Python/issues/45
I have moved the Chat class into my own code, and have the following:
def __init__(self, channel: str, nickname: str, oauth: str, helix: Optional['twitch.Helix'] = None):
super().__init__()
self.helix: Optional['twitch.Helix'] = helix
self.irc = tc.IRC(nickname, password=oauth)
self.irc.incoming.subscribe(self._message_handler)
self.irc.start()
self.channel = channel.lstrip('#')
self.joined: bool = False
print(self.irc.is_alive())
The class is called with two different functions elsewhere, like so:
def handle_message(self, message : twitch.chat.Message) -> None:
print(message.sender, message.text)
def main(self):
ircConn = TCH(channel='#CHANNEL NAME", nickname="BOT NAME", oauth="SAMPLEOAUTH")
ircConn.subscribe(self.handle_message)
The issue is that about 1 in 6 times, the subscribe() doesn't actually do anything and the program ends. I'd like to find a way to detect when it fails, so that I may attempt a retry, but nothing I've found works. The function/class doesn't return anything, adding an on_error or on_completed argument to the subscribe() doesn't call anything, and using sys.excepthook also doesn't catch it failing.
Additionally, the IRC thread always prints True for irc.is_alive(), even when it fails afterwards.
How can I catch the thread failing? Thank you.
Is there any official support for the new Discord slash commands; if not, how do you use the discord-py-slash-command module as I couldn't get that to work
I've been spending a while trying to work out how to use the new slash commands and I couldn't find Discord saying how to use it on discord.py.
After a bit of searching I've found a module called discord-py-slash-command but I couldn't figure out how to use this either.
When I tried to implement it into the main code of my bot nothing happened, so I tried to just run the example they showed on their website here (The top example) without modifying it and that also didn't work, and return this error message:
Traceback (most recent call last):
File "/snap/pycharm-community/224/plugins/python-ce/helpers/pydev/pydevd.py", line 2167, in <module>
main()
File "/snap/pycharm-community/224/plugins/python-ce/helpers/pydev/pydevd.py", line 2034, in main
debugger = PyDB()
File "/snap/pycharm-community/224/plugins/python-ce/helpers/pydev/pydevd.py", line 407, in __init__
self._cmd_queue = defaultdict(_queue.Queue) # Key is thread id or '*', value is Queue
AttributeError: module 'queue' has no attribute 'Queue'
Process finished with exit code 1
Here's my copy and pasted code from their example:
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash import SlashContext
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
slash = SlashCommand(bot)
#slash.slash(name="test")
async def _test(ctx: SlashContext):
embed = discord.Embed(title="embed test")
await ctx.send(content="test", embeds=[embed])
bot.run(".token.txt")
I'm not very qualified with discord-py-slash-command but as far as I know, you have to pass some arguments in #slash.slash() such as description etc.
guild_ids = [<your guild id>]
slash = SlashCommand(bot, auto_register=True)
#slash.slash(
name="ttest",
description="Sends message.",
guild_ids=guild_ids
)
async def _test(ctx: SlashContext):
embed = discord.Embed(title="embed test")
await ctx.send(content='test', embeds=[embed])
This will work but I don't recommend you to use this module until it's references became more clear. It's so unclear and unhandy also it's syntax is so complicated compared to discord.py.
Also, you have to enable applications.commands scope from Discord Developer Portal -> OAuth2 -> Scopes.
I've recently been building a bot with discord-py-slash-command. I've figured out that the best way to make a command would be to read their documentation (below).
With your command, what I notice first that I haven't used is ctx: SlashContext, instead, try using just ctx. Your script is also probably you used Embeds=[embed], and I am not sure how multiple embeds would work, but for a single one, embed= is lowercase. I'm pretty sure you don't need the content=''.
The errors seems to be coming from pycharm and not the script itself, maybe try another IDE.
Documentation:
https://discord-py-slash-command.readthedocs.io/en/latest/
Option Types (I found this really useful):
https://discord-py-slash-command.readthedocs.io/en/latest/discord_slash.model.html?highlight=USER#discord_slash.model.SlashCommandOptionType.USER
My discord is _stefthedoggo#1698, DM me if you want more help, I have a working bot running solely on discord-py-slash-commands
Is it possible to delete all chat history(messages) of my chat with bot.
So the console version be like:
import os
os.sys("clear") - if Linux
os.sys("cls") - if Windows
All I want is to delete all messages in chat using bot.
def deleteChat(message):
#delete chat code
First of all, if you want to delete history with a bot you should save message ids.
Otherwise, you could use an userbot (using an user account) for clearing it.
You can iter all chat messages and get their ids, and delete them in chunks of 100 messages each iteration.
Warning: itering message history of a chat is not possible with bots and BotAPI, because of Telegram limits. So you should use an MTProto API framework, with an user account as said before.
First of all, pyrogram library is needed for doing this (you could also use telethon), and instance a Client, then you can add an handler or start Client using with keyword. Then get all messages ids by itering the chat, and save them in a list. Finally, delete them using delete_messages Client method:
import time, asyncio
from pyrogram import Client, filters
app = Client(
"filename", # Will create a file named filename.session which will contain userbot "cache"
# You could also change "filename" to ":memory:" for better performance as it will write userbot session in ram
api_id=0, # You can get api_hash and api_id by creating an app on
api_hash="", # my.telegram.org/apps (needed if you use MTProto instead of BotAPI)
)
#app.on_message(filters.me & filters.command("clearchat") & ~filters.private)
async def clearchat(app_, msg):
start = time.time()
async for x in app_.iter_history(msg.chat.id, limit=1, reverse=True):
first = x.message_id
chunk = 98
ids = range(first, msg.message_id)
for _ in (ids[i:i+chunk] for i in range(0, len(ids), chunk)):
try:
asyncio.create_task(app_.delete_messages(msg.chat.id, _))
except:
pass
end = time.time() - start
vel = len(ids) / end
await msg.edit_text(f"{len(ids)} messages were successfully deleted in {end-start}s.\n{round(vel, 2)}mex/s")
app.run()
Once you start the userbot, add it in a group, and send "/clearchat". If the userbot has delete messages permission, it will start deleting all messages.
For pyrogram documentation see https://docs.pyrogram.org.
(however, you should not print all messages in the terminal, to avoid server overloading)
And the right code for clearing the console is this:
import os
def clear():
os.system("cls" if os.name == "nt" else "clear")
as seen in How to clear the interpreter console?.
P.S.
You can use the same code, adding bot_token="" parameter to Client, and deleting iter_history part, for deleting messages with a bot if you have the messages ids.
If in the future you'll want to receive messages from a group and print them, but you don't receive the message update, add the bot as admin in the group or disable bot privacy mode in BotFather.
For better pyrogram performance, you should install tgcrypto library.
Hello People I'm building an irc bot using python twisted, everything is built but the bot doesn't respond to commands like i want it to. For example if i want to call a bot command on the irc channel i want to be able to call it like this $time and have the bot reply what time it is, i am able to get it to work like this -> crazybot $time and it prints the time but i don't want to have to type the name every time...How do i get the the bot to run the commands without calling the name first ?
Here is the update -> everything connects
.......
def privmsg(self, user, channel, msg):
user = user.split('!', 1)[0]
if not msg.startswith('#'): # not a trigger command
return # do nothing
command, sep, rest = msg.lstrip('#').partition(' ')
func = getattr(self, 'command_' + command, None)
def command_time(self, *args):
return time.asctime()
....
When i type !time there is no error and no output ..
You could modify MyFirstIrcBot:
Replace ! by $ in:
if not message.startswith('!'): # not a trigger command
return # do nothing
command, sep, rest = message.lstrip('!').partition(' ')
Add:
from datetime import datetime
# ...
def command_time(self, rest):
return datetime.utcnow().isoformat()