0

So, I am making a discord bot and recently I updated my ubuntu server. When I later tried to host the discord bot in my ubuntu server the code is returning "RuntimeWarning: coroutine 'setup' was never awaited" and I can't figure out why the code wont work after the system update. When I created the discord bot I wrote it on my windows machine and transported it over to linux and mixed some things up so that it would match linux, example the os.system("cls") on windows => os.system("clear") on linux. I can run the code on windows but not on linux. The bot gets online but doesn't responde to commands.

Some strings/comments may be in Swedish since I am Swedish and the bot too :)

ERROR MESSAGE:

Bot is starting...
/home/johan/discord/abdi/bot.py:32: RuntimeWarning: coroutine 'setup' was never awaited
  cogs[i].setup(bot)
Object allocated at (most recent call last):
  File "/home/johan/discord/abdi/bot.py", lineno 32
    cogs[i].setup(bot)
Bot logged in as: mybotstagishere
Bot is online and ready
Logging:

|

I am using multiple code files so it can be organized; MAIN CODE:

#Import
import discord
import tracemalloc
from discord.ext import commands
import os
from datetime import date
#Cog import
import music
import normalcommands
import events
import economy
import asyncio

#Setup
os.system("clear")
print("Bot is starting...")

intents = discord.Intents.default()
#intents = discord.Intents.all()
intents.members = True
intents.reactions = True
#case_insensitive=True sätt den i bot =>

PREFIX = "!"
TOKEN = "blablaiamnotgoingtogiveyoumytokenheheheblabla"
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix=PREFIX, intents=intents, )
cogs = [music, normalcommands, events, economy]

tracemalloc.start()
for i in range(len(cogs)):
    cogs[i].setup(bot)

#Startup prints
@bot.event
async def on_ready():
    print("Bot logged in as: {0.user}".format(bot))
    print("Bot is online and ready")
    print("Logging:")
    print()
    print("|")

#Logs
@bot.event
async def on_message(message):
    username = str(message.author).split("#")[0]
    user_message = str(message.content)
    #channel = str(message.channel.name)

    #Logging
    if message.author == bot.user:
        return
    else:
        fullstring = user_message
        substring = PREFIX
        if fullstring.find(substring) != -1:
            date.today()
            print(date.today())
            print(f"{username}: {user_message}")
            print("|")
        else:
            pass
    await bot.process_commands(message)

#Info
@bot.command(aliases=["om", "hjälp"])
async def info(ctx):
    await ctx.send(f"Vanliga kommandon:**!ping, !random (min) (max), !rickroll, !blötfis,     !hogrida, !beinis (personen).** **Musik kommandon: !play (url/namn), !loop, !join, !leave,     !queue, !clearqueue, !stop, !pause, !resume, !skip. På vissa av musik kommandona kan man             bara ta första bokstaven, exempel !j som är !join. Ekonomi system kommer senare!**")

#Startup
bot.run(TOKEN)

MUSIC CODE:

#Import
import discord
from discord.ext import commands
import requests
from youtube_dl import YoutubeDL
from discord import FFmpegPCMAudio
import asyncio

#Inställningar
YDL_OPTIONS = {
    'format': 'bestaudio/best', 
    'noplaylist': True,
    'prostprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '256',
    }]
    }
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}

#Variablar


#Funktioner
def search(query):
        with YoutubeDL(YDL_OPTIONS) as ydl:
            try:
                requests.get(query)
            except:
                info = ydl.extract_info(f"ytsearch:{query}", download=False)['entries'][0]
            else:
                info = ydl.extract_info(query, download=False)
        return (info, info['formats'][0]['url'])
def play_next(self,ctx):
    vc = ctx.voice_client
    song_queue = self.song_queue
    if len(song_queue) >= 1:
        query = song_queue[0] 
        video, source = search(query)
        del song_queue[0]
        vc.play(discord.FFmpegPCMAudio(source=source, **FFMPEG_OPTIONS), after=lambda e: after_song(self, ctx))
        asyncio.run_coroutine_threadsafe(ctx.send(f"Nu spelas: **{video['title']}**"), self.bot.loop)
        vc.is_playing()
        #asyncio.run_coroutine_threadsafe(self.bot.loop)
    else:
        pass
def after_song(self,ctx):
    if self.loop_activate == False:
        try:
            del self.current_song[:]
        except:
            pass
        play_next(self,ctx)
    elif self.loop_activate == True:
        song_queue = self.song_queue
        del song_queue[:]
        query = self.current_song
        video, source = search(query)
        vc = ctx.voice_client

        vc.play(discord.FFmpegPCMAudio(source=source, **FFMPEG_OPTIONS), after=lambda e: after_song(self,ctx))
        vc.is_playing()
        

#Program
class music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    #@commands.Cog.listener() / @bot.event():
    #@commands.command() / @bot.command():
    #---------------------------------------------------

    #Spel listor
    song_queue = []
    current_song = []
    loop_activate = False
    
    #Spela
    @commands.command(aliases=["p", "spela"])
    async def play(self,ctx,*,query):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)
        member_voice = ctx.author.voice
        if member_voice and member_voice.channel:
            if ctx.voice_client:
                pass
            else:
                try:
                    await member_voice.channel.connect()
                except:
                    await ctx.send("Lyckades inte joina vc! Kan ha med perms på röst kanalen.")
        vc = ctx.voice_client
        video, source = search(query)
        self.current_song.append(video['title'])
        if not vc.is_playing():
            #Uppspelning
            vc.play(discord.FFmpegPCMAudio(source=source, **FFMPEG_OPTIONS), after=lambda e: after_song(self,ctx))
            vc.is_playing()
            await ctx.send(f"Nu spelas: **{video['title']}**")
        else:
            self.song_queue.append(video['title'])
            await ctx.send(f"**{video['title']}** har lagts till i kön!")

    #Repeat
    @commands.command(aliases=["upprepa", "repeat"])
    async def loop(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)
        song_queue = self.song_queue
        del song_queue[:]
        if self.loop_activate == True:
            self.loop_activate = False
            await ctx.send("Upprepning är avstängt!")
        else:
            self.loop_activate = True
            await ctx.send(f"Upprepning är på!")

    #Join
    @commands.command(aliases=["j", "joina", "gåmed"])
    async def join(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)    
        member_voice = ctx.author.voice
        if member_voice and member_voice.channel:
            if ctx.voice_client:
                pass
            else:
                try:
                    await member_voice.channel.connect()
                except:
                    await ctx.send("Kunde inte gå med i samtalet:cry:, kan bero på att det är privat eller att du inte sitter i något samtal! Om jag redan sitter i ett samtal så måste du dra mig till ditt samtal.")

    #Visa kön
    @commands.command(aliases=["kö", "visakö"])
    async def queue(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)    
        song_queue = self.song_queue
        song_queue_length = len(song_queue)

        song_queue_str = str(song_queue)
        song_queue_str1 = song_queue_str.replace("[", "")
        song_queue_str2 = song_queue_str1.replace("]", "")
        song_queue_str3 = song_queue_str2.replace("'", "")

        song_queue_show = song_queue_str3

        if song_queue == []:
            await ctx.send(f"Finns inget på kö!")
        else:
            await ctx.send(f"Det är {song_queue_length} låt/ar på kö! Kön ser ut såhär: **{song_queue_show}**")

    #Töm kön
    @commands.command(aliases=["clearqueue", "töm", "tömkön"])
    async def clear(self,ctx):
        song_queue = self.song_queue
        del song_queue[:]

    #Stoppa
    @commands.command(aliases=["stop", "restart"])
    async def stopp(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)
        self.current_song = []
        self.loop_activate = False
        song_queue = self.song_queue
        del song_queue[:]
        vc = ctx.voice_client
        vc.stop()

    #Lämna samtal
    @commands.command(aliases=["leave", "l"])
    async def lämna(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)

        member_voice = ctx.author.voice
        if member_voice and member_voice.channel:
            if ctx.voice_client:
                if member_voice.channel == ctx.voice_client.channel:
                    try:
                        await ctx.voice_client.disconnect()
                    except:
                        await ctx.send("Kunde inte lämna!")
                else:
                    await ctx.send("Du måste vara i samma samtal som mig!")    
            else:
                pass

    #Pausa
    @commands.command(aliases=["pausa"])
    async def pause(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)

        vc = ctx.voice_client
        try:
            vc.pause()
        except:
            await ctx.send("Lyckades inte pausa!")

    #Fortsätt spela
    @commands.command(aliases=["continue", "r", "fortsätt"])
    async def resume(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji)

        vc = ctx.voice_client
        try:
            vc.resume()
        except:
            await ctx.send("Lyckades inte fortsätta spela upp!")

    #Skippa
    @commands.command(aliases=["s", "hoppa", "skip"])
    async def skippa(self,ctx):
        emoji = '\N{THUMBS UP SIGN}'
        await ctx.message.add_reaction(emoji) 

        vc = ctx.voice_client
        try:
            vc.stop()
        except:
            await ctx.send("Kunde inte skippa!")


#Add cog
async def setup(bot):
    await bot.add_cog(music(bot))

1 Answers1

0

Your setup function in your separate modules like music is an async function, and if you notice in line 32 cogs[i].setup(bot) is not awaited where you're calling it in the loop. In order to await in the iteration, you may use a wait wrapper around a list of tasks containing your setup calls.

def init_configs(bot):
    loop = asyncio.get_event_loop()
    tasks = [config.setup(bot) for config in cogs]
    loop.run_until_complete(asyncio.wait(tasks))

init_configs(bot)
# ...

Or if you want to use async/await:

import asyncio

async def init_configs(bot):
    tasks = [config.setup(bot) for config in cogs]
    await asyncio.wait(tasks)
import asyncio
# ...
async def main():
    await init_configs(bot)
    # All the bot codes like:
    @bot.event
    async def on_message(message):
        # ...
    
asyncio.run(main())
Momo
  • 794
  • 2
  • 7
  • 17
  • Thanks I got rid of the error, but the bot is not detecting the commands. I have replaced line 31 and 32 with your code example. Maybe I need to call the function, but how and where? – Snabba_Snigeln Oct 09 '22 at 18:57
  • @Snabba_Snigeln Yeah, my bad, I should have mentioned that you should call it! I updated the answer for both use cases. – Momo Oct 09 '22 at 20:35
  • I still can't seem to figure it out, I am new to programming so I may have missed something. I have inserted your first example of code in to line 32, 31 and it keeps giving me "TypeError: setup() missing 1 required positional argument: 'bot'". – Snabba_Snigeln Oct 10 '22 at 14:38
  • @Snabba_Snigeln I forgot to pass `bot` for `config.setup`. Answer edited! – Momo Oct 10 '22 at 15:27
  • I got rid of the TypeError problem. Now it's telling me "DeprecationWarning: There is no current event loop". Exact problem goes here; "/home/johan/discord/abdi/bot.py:32: DeprecationWarning: There is no current event loop (new line) loop = asyncio.get_event_loop()" – Snabba_Snigeln Oct 10 '22 at 19:03
  • @Snabba_Snigeln Since I do not have your code and bot stuff to test, can you please try the second method and say the result? – Momo Oct 10 '22 at 19:33
  • Yes, here is the error on theasync/await solution: "RuntimeError: Cannot run the event loop while another loop is running (new line and some other error text) sys:1: RuntimeWarning: corountine 'Client.run.runner' was never awaited. Since the error was too long to pase into the comments I can't provide you with the full output, just tell me if you need more of the error output :D – Snabba_Snigeln Oct 11 '22 at 14:37
  • @Snabba_Snigeln Does https://stackoverflow.com/a/56434301/12696223 solve the problem? – Momo Oct 11 '22 at 22:05
  • Sorry for my late response. I have tried to transfer the clean files from my windows machine over to the linux server again and modifed the os.system("cls") to match linux and now it seems to be working fine. Looks like all it needed was some clean files.... – Snabba_Snigeln Oct 15 '22 at 09:25