Task:
I made this command that should create a file .txt file and if it has a valid name and it does not exist in ListPython.txt. But when I run it I get the error bellow. Could someone please help me?
Code:
#bot.tree.command(name="newpython")
#app_commands.describe(FileName='FileName')
async def newpython(interaction: discord.Interaction,FileName: str):
AddToLog(f'[INFO][{GetTime()}] newpython command has been used')
_ = open("Program Files/ListPython.txt", "r")
_ = _.read()
_ = _.split()
if FileName not in _:
with open("Program Files/ListPython.txt", "a") as file1:
file1.write(f' {FileName}')
try:
f = open(f"Python Files/{FileName}.txt", "x")
await interaction.response.send_message(f"{FileName} created")
except OSError:
await interaction.response.send_message(f"{FileName} is a invalid file name.")
else:
await interaction.response.send_message(f"{FileName} already exists.")
Error:
discord.app_commands.errors.CommandSignatureMismatch: The signature for command 'newpython' is different from the one provided by Discord. This can happen because either your code is out of date or you have not synced the commands with Discord, causing the mismatch in data. It is recommended to sync the command tree to fix this issue.
The problem is not for app_commands because when I removed it I still got the error though I could be wrong because I'm new to discod.py.
I solved the problem with replacing:
#app_commands.describe(FileName='FileName')
with
#app_commands.describe(user='FileName')
I really don't know how this fix the problem but it does
Related
#Recording voice input using microphone
file = "file.mp3"
flag=True
fst="My name is Dan. I will answer your queries about Science. If you want to exit, say Bye"
tts = gTTS(fst, 'en')
tts.save(file)
os.system("mpg123 " + file )
r = sr.Recognizer()
prYellow(fst)
I am working with this error in this area using python and I cannot fix it. Hoping that there's anyone here who can fix this error problem.
I'm trying to change the help command to use a pagination version of help.
I understand that the following line of code removes the help command entirely:
bot.remove_command('help')
The docs/dicord.py server offer the following example as a way to change the default help command:
class MyHelpCommand(commands.MinimalHelpCommand):
def get_command_signature(self, command):
return '{0.clean_prefix}{1.qualified_name} {1.signature}'.format(self, command)
class MyCog(commands.Cog):
def __init__(self, bot):
self._original_help_command = bot.help_command
bot.help_command = MyHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command
I'm still a newbie in python, and I've only been learning rewrite for about 3 days - I'm struggling to find any working examples or an explanation that doesn't lead me back to the above code. I can't work out how to implement this into my own code - so my question is, could anyone provide further explaination into how this would be implemented using cogs?
You can use help_command=None. It delete default help command and you can create your help command. Example:
bot = commands.Bot(command_prefix='!', help_command=None)
#bot.command()
async def help(context):
await context.send("Custom help command")
If you don't set help_command=None and try to create your help command, you get this error: discord.errors.ClientException: Command help is already registered.
You don't really need to remove the command... It isn't good, using the (prefix)help commandname <- It wont appear then... If you want it embed you can do.
class NewHelpName(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page)
await destination.send(embed=emby)
client.help_command = NewHelpName()
The built in help command is of great use
import os
async def cmdrun(client, message, prefix):
cmd = message.content.split(' ')[0].split(prefix)[1]
args = message.content.split(cmd)[1][1:].split(' ')
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
imported = filename.split('.py')[0]
strin = f"from commands.{imported} import name, aliases, run\nx = name()\ny = aliases()\nawait message.channel.send(x + y)\nif x == {cmd} or {cmd} in y:\n await run(client, message, args)"
exec(strin)
I am making a discord bot with discord.py.
What is the error
That error is definitely always associated with a missing double-inverted/single-inverted comma. Here's my suggestions:
Try running the prepared lines of code you're attempting to use as is.
I couldn't find anything in the new documentation, but the old
documentation suggest that ...in the current implementation, multi-line compound statements must end with a newline: exec "for v in seq:\n\tprint v\n" works, but exec "for v in seq:\n\tprint v" fails with SyntaxError. Perhaps try adding a new line character at the end?
Try using triple inverted commas.
Hope this solves the issue!
For some reason I keep getting an invalid syntax error of my code on Debian. But when I run it on my mac nothing wrong happens and it runs smooth. Could you guys help me?
def read_config(cfg='~/instacron/config.txt'):
"""Read the config.
Create a config file at `cfg` with the
following information and structure:
my_user_name
my_difficult_password
"""
import os.path
_cfg = os.path.expanduser(cfg)
try:
with open(_cfg, 'r') as f:
user, pw = [s.replace('\n', '') for s in f.readlines()]
except Exception:
import getpass
print(f"\nReading config file `{cfg}` didn't work")
user = input('Enter username and hit enter\n')
pw = getpass.getpass('Enter password and hit enter\n')
save_config = input(
f"Save to config file `{cfg}` (y/N)? ").lower() == 'y'
if save_config:
os.makedirs(os.path.dirname(_cfg), exist_ok=True)
with open(_cfg, 'w') as f:
f.write(f'{user}\n{pw}')
return {'username': user, 'password': pw}`
print(f"\nReading config file `{cfg}` didn't work")
^
SyntaxError: invalid syntax
f-strings (f"{var}") were only added to Python in version 3.6; earlier versions do not accept them. Your Debian and Mac are clearly running different versions of Python, only one of which is at least 3.6.
The following code works almost perfect, thanks to the help received here:
import urllib.request
import zipfile
import subprocess
urls = ["http://url.com/archive1.zip", "http://url.com/archive2.zip", "http://url.com/archive3.zip"]
filename = "C:/test/test.zip"
destinationPath = "C:/test"
for url in urls:
try:
urllib.request.urlretrieve(url,filename)
sourceZip = zipfile.ZipFile(filename, 'r')
break
except ValueError:
pass
for name in sourceZip.namelist():
sourceZip.extract(name, destinationPath)
sourceZip.close()
subprocess.call(r'C:\WINDOWS\system32\cmd.exe /C "C:\test\test.exe"')
Except that when none of the url's successfully download, the final subprocess.call command never gets executed and I get the following error:
Traceback (most recent call last):
File "test.py", line 29, in <module>
for name in sourceZip.namelist():
NameError: name 'sourceZip' is not defined
I have been playing around a bit with the try: and except, but can not come to a working solution. I believe it is because the try: except command has to be inside the sourceZip loop, but since the sourceZip variable never gets declared, it fails. How would I alter this code to have the subprocess.call always get executed at the end regardless whether the download is successfull or not? (very new to Python)
Set sourceZip = None prior to the for url in urls line. Then test if sourceZip is None after the for loop to determine if you were able to successfully fetch the file. For example:
sourceZip = None
for url in urls:
try:
urllib.request.urlretrieve(url,filename)
sourceZip = zipfile.ZipFile(filename, 'r')
break
except ValueError:
pass
if sourceZip is not None:
for name in sourceZip.namelist():
sourceZip.extract(name, destinationPath)
sourceZip.close()
subprocess.call(r'C:\WINDOWS\system32\cmd.exe /C "C:\test\test.exe"')
Initialize sourceZip to None. Then check if it is not none do the extraction and closing.