Home > Blockchain >  How can I send a message through a separate function for my discord bot in python?
How can I send a message through a separate function for my discord bot in python?

Time:10-28

I'm writing a little Discord bot I want to use for my own personal server and I wanted to try putting all the command keywords into an array and having a function for each command to keep my code neat. Sorry if that sounds stupid, but I'm pretty new to Python. I want to try a basic spam command to test my bot, but whenever I try to make it send a message through the function I get this error:

File "main.py", line 31
    await message.channel.send(f"spam")
    ^
SyntaxError: 'await' outside async function

Here is my code:

import discord
import os
import time
token = os.environ['token']

client = discord.Client()
keywords = ["spam"]

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))


@client.event
async def on_message(message):
    prefix = "."
    if message.author == client.user:
        return

    if message.content.startswith(prefix):
        mcontent = (str(message.content))[1:len(str(message.content))]
        for i in range(len(keywords)):
          if keywords[0] in mcontent:
            spam(mcontent, message)


def spam(mcontent, message):
  n = int(mcontent[4:len(mcontent)])
  n2 = 0
  while n2 < n:
    await message.channel.send(f"spam")
    n2 = n2   1
    time.sleep(1)

client.run(token)

CodePudding user response:

You forgot to make the function async:

async def spam(mcontent, message):
    ...
  • Related