I am trying write discord bots using Python, I have come across and threw together this bot.
import discord
import asyncio
import random
client = discord.Client()
inEmail = input("Email:")
inPassword = input("Passwd:")
async def background_loop():
await client.wait_until_ready()
while not client.is_closed:
channel = client.get_channel("************")
messages = ["Hello!", "How are you doing?", "Testing!!"]
await client.send_message(channel, random.choice(messages))
await asyncio.sleep(120)
client.loop.create_task(background_loop())
client.run(inEmail, inPassword)
Yet when I tried to run it, I received a SyntaxError
:
File "1.py", line 7
async def background_loop():
^
SyntaxError: invalid syntax
Why is that? I have never received that before when I tested it.
Rohit Patel
Asynchronous requests were introduced to Python in v3.3, if you’re running Python prior to v3.3 (including v2.X), you’ll have to install a newer version of Python.
Only if you are running Python 3.3:
asyncio
is not part of the stdlib, you’ll need to install it manually from pypi:The
async
andawait
keywords are only valid for Python 3.5 or newer. If you’re using Python 3.3 or 3.4, you will need to make the following changes to your code:@asyncio.coroutine
decorator instead of theasync
statement:yield from
instead ofawait
:Here is an example of what your function need to change into (if you’re on 3.3-3.4):
The aforementioned syntax is still supported in newer versions of Python 3, but it is recommended to use
await
andasync
if there’s no need to support for Python 3.3-3.4. You can refer back to this documentation, here’s a short snippet:Aside:
discord.py currently supports 3.4.2-3.6.6, (It does not support 3.3-3.4.1, 3.7 as of January 2019).
For developing with discord.py, I suggest using the discord.py rewrite branch:
discord.py-rewrite supports 3.5.3-3.7.