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))