Async def invalid syntax - Python Help - Discussions on Python.org
Async def invalid syntax Python Help help NotFakeAmigo (NotFakeAmigo) March 6, 2021, 11:50pm 1 Hello, today I copied bot from GitHub, but when I wanted to run that bot so it throw this error: File "/home/Bot/bot.py", line 30 async def on_ready(): ^ SyntaxError: invalid syntax This is my code: import os import discord import json import logging import sys from discord.ext import commands, tasks from discord.ext.commands import has_permissions, MissingPermissions from dotenv import load_dotenv import aiohttp import mimetypes import asyncio # import subprocess bot = commands.Bot(command_prefix=".", intents=discord.Intents.default(), case_insensitive=True) load_dotenv() token = os.getenv('BOT TOKEN') logging.basicConfig(filename='console.log', level=logging.INFO, format='[%(asctime)s %(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S', ) logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) @bot.event async def on_ready(): # Marks bot as running logging.info('I am running.') @bot.event async def on_message(message): # Binflop if len(message.attachments) > 0: if not message.attachments[0].url.lower().endswith(('.html')): file_type = mimetypes.guess_type(message.attachments[0].url) if not file_type[0] == None: try: file_type = file_type[0].split('/')[0] except: logging.info(file_type + " failed while being parsed") if message.attachments[0].url.lower().endswith(('.log', '.txt', '.json', '.yml', '.yaml', '.css', '.py', '.js', '.sh', '.config', '.conf')) or file_type == 'text': text = await discord.Attachment.read(message.attachments[0], use_cached=False) text = text.decode('Latin-1') text = "\n".join(text.splitlines()) truncated = False if len(text) > 100000: text = text[:99999] truncated = True async with aiohttp.ClientSession() as session: async with session.post('https://bin.birdflop.com/documents', data=text) as req: key = json.loads(await req.read())['key'] response = "" response = response + "https://bin.birdflop.com/" + key response = response + "\nRequested by " + message.author.mention if truncated: response = response + "\n(file was truncated because it was too long.)" embed_var = discord.Embed(title="Please use a paste service", color=0x1D83D4) embed_var.description = response await message.channel.send(embed=embed_var) logging.info(f'File uploaded by {message.author} ({message.author.id}): https://bin.birdflop.com/{key}') timings = bot.get_cog('Timings') await timings.analyze_timings(message) await bot.process_commands(message) @bot.command() async def ping(ctx): await ctx.send(f'Birdflop bot ping is {round(bot.latency * 1000)}ms') @bot.command() async def invite(ctx): await ctx.send('Invite me with this link:\nhttps://discord.com/oauth2/authorize?client_id=787929894616825867&permissions=0&scope=bot') @bot.command(name="react", pass_context=True) @has_permissions(administrator=True) async def react(ctx, url, reaction): channel = await bot.fetch_channel(int(url.split("/")[5])) message = await channel.fetch_message(int(url.split("/")[6])) await message.add_reaction(reaction) logging.info('reacted to ' + url + ' with ' + reaction) for file_name in os.listdir('./cogs'): if file_name.endswith('.py'): bot.load_extension(f'cogs.{file_name[:-3]}') bot.run(token) # full name: message.author.name + "#" + str(message.author.discriminator) + " (" + str(message.author.id) + ")" How can I solve this error? steven.daprano (Steven D'Aprano) March 7, 2021, 12:11am 2 What version of Python are you using?
Check the previous line(s) for missing close brackets. NotFakeAmigo (NotFakeAmigo) March 7, 2021, 7:47am 3 I am using python3.7. steven.daprano (Steven D'Aprano) March 7, 2021, 8:11am 4 I cannot replicate that syntax error with your code. Are you sure you are looking at the correct file? If you have two or more versions of the file, maybe you are looking at the wrong one. NotFakeAmigo (NotFakeAmigo) March 7, 2021, 8:34am 5 I am looking in the correct file, on line 30 is this: @bot.event async def on_ready(): # Marks bot as running logging.info('I am running.') steven.daprano (Steven D'Aprano) March 7, 2021, 11:05am 6 When I copy your code into a file, and run it with Python 3.7, I do not get a syntax error.
The code you give is valid syntax for Python 3.7. There are only three possibilities: you gave us the correct code, but you are not using Python 3.7; you are using 3.7, but the code you gave us is not the code you are trying to run; you are using 3.7, and the code you gave is the correct code, but you aren’t getting a SyntaxError. steven.daprano (Steven D'Aprano) March 7, 2021, 11:09am 7 How are you running your code?
Are you using an IDE, or running it from the command line? If you are running it from the command line, can you copy and paste the exact command you are using please. NotFakeAmigo (NotFakeAmigo) March 7, 2021, 11:21am 8 I am running it in linux (debian 10), I used supervisorctl start all (I had it configured, but maybe is something wrong with it) so command is supervisorctl start all steven.daprano (Steven D'Aprano) March 7, 2021, 11:37am 9 You said: “so command is supervisorctl start all” And what does that command do?
I am willing to bet that it is calling Python 2.7 not Python 3.7. What happens when you call python3.7 myscript.py where “myscript” is replaced by the actual path to your script? NotFakeAmigo (NotFakeAmigo) March 7, 2021, 11:43am 10 -bash: python3.7: command not found kpfleming (Kevin P. Fleming) March 7, 2021, 12:51pm 11 It appears that you do not have Python 3.7 installed on your system. NotFakeAmigo (NotFakeAmigo) March 7, 2021, 1:03pm 12 I installed now python3.7, but I am now getting this error: Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Fatal Python error: initfsencoding: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f43c577b740 (most recent call first): Aborted kpfleming (Kevin P.
Fleming) March 7, 2021, 1:12pm 13 What commands did you run to install Python 3.7? NotFakeAmigo (NotFakeAmigo) March 7, 2021, 1:12pm 14 apt install python3.7 pepoluan (Pandu E POLUAN) March 7, 2021, 1:45pm 15 How do you configure your program? NotFakeAmigo (NotFakeAmigo) March 7, 2021, 1:52pm 16 I can run that bot with python3.7 bot.py, but when I try to use commands python3.7, pip it will do this: root@debian:~# python3.7 Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] Fatal Python error: initfsencoding: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f34a9d2a740 (most recent call first): Aborted kpfleming (Kevin P.
Fleming) March 7, 2021, 9:17pm 17 Your Python 3.7 installation is broken, somehow. You’ll need to find someone who is familiar with the Linux distribution you are using to try to figure out what is wrong. Pemigrade (Purpur) March 25, 2021, 1:26am 18 Hey, I wrote the GitHub repository you’re referencing that contains that code. There’s a support link in the readme, if you still haven’t solved the issue and want to seek support from there.
From what you’ve sent here, it should work. Your Python installation being broken is the highest likelihood.