Replaces asyncio coroutines with native async

Replaces @asyncio.coroutine decorator with async
Replaces yield from with await
This commit is contained in:
2022-12-18 02:03:46 +01:00
parent ad2324d53c
commit f8db215b31
4 changed files with 124 additions and 163 deletions
+30 -38
View File
@@ -1,4 +1,3 @@
import asyncio
import discord
from discord.ext import commands
import numpy as np
@@ -28,17 +27,16 @@ class Chatbot(commands.Cog):
#Do stuff when a message comes in:
@self.bot.event
@asyncio.coroutine
def on_message(message):
async def on_message(message):
if message.author.bot:
return #ignore your own messages, Stroop
if message.content.strip() == "" or message.content.strip()[0] != '!': #don't respond to a command
if message.content.lower() == "nihao":
yield from message.channel.send("kankerlauw")
await message.channel.send("kankerlauw")
return
if message.content.lower() == "lol":
yield from message.channel.send("laffing aut laut")
await message.channel.send("laffing aut laut")
return
if self.bot.user.mentioned_in(message) and "@everyone" not in message.content:
MENTIONED_RESPONSES = [
@@ -52,32 +50,32 @@ class Chatbot(commands.Cog):
MENTIONED_RESPONSES.append("Wat mot je, " + random.choice(self.bot.get_cog("Shitpost").insult) + "?")
except:
print("ERROR! - Could not import insults")
yield from message.channel.send(random.choice(MENTIONED_RESPONSES))
await message.channel.send(random.choice(MENTIONED_RESPONSES))
return
if re.match("^[0-9]+([,.]?[0-9]+)*?$", message.content.strip()) and random.randint(0,9) == 0:
yield from message.channel.send("That's Numberwang!") # https://www.youtube.com/watch?v=0obMRztklqU
await message.channel.send("That's Numberwang!") # https://www.youtube.com/watch?v=0obMRztklqU
return
if "DMChannel" in type(message.channel).__name__: #respond to messages in PM channels
if (self.isAllowedToLearnFromPm(message)): #avoid spam-learning
self.pmCount += 1
self.pmLast = datetime.now()
yield from self.learnFromMessagesInChannel(message.channel, 1)
yield from self.respondToMessage(message)
await self.learnFromMessagesInChannel(message.channel, 1)
await self.respondToMessage(message)
elif message.channel.id == self.bot.hdChannels["belangrijk"]: #don't abuse the "belangrijk" channel
pass
else:
a = random.randint(0,999) # probablity
if a < 40:
yield from self.learnFromMessagesInChannel(message.channel, 10)
await self.learnFromMessagesInChannel(message.channel, 10)
if "stroop" in message.content.lower():
a = a / 20 # significantly increase the chance of responding if somebody talks about him.
if message.channel.id == self.bot.hdChannels["shitpost"] and a < 40: #shitpost channel
yield from self.respondToMessage(message)
await self.respondToMessage(message)
elif a < 10: #all other channels
yield from self.respondToMessage(message)
await self.respondToMessage(message)
#process commands:
yield from self.bot.process_commands(message)
await self.bot.process_commands(message)
def __check(self, ctx):
return True
@@ -183,22 +181,20 @@ class Chatbot(commands.Cog):
@commands.command(pass_context=True, hidden=True)
@asyncio.coroutine
def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
async def trainmarkovchat(self, ctx, channelId=409751773595566081, nrOfMessages=50):
"""Train that chain, jermaine
param channelId: use this channel to train
param nrOfMessages: use the x most recent messages
"""
channel=self.bot.get_channel(channelId)
yield from self.learnFromMessagesInChannel(channel, nrOfMessages)
await self.learnFromMessagesInChannel(channel, nrOfMessages)
yield from ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
await ctx.channel.send("Ik heb weer wat nieuwe woordjes geleerd. :slight_smile:")
#Learns from an x number of messages from a certain channel
@asyncio.coroutine
def learnFromMessagesInChannel(self, channel, nrOfMessages):
async def learnFromMessagesInChannel(self, channel, nrOfMessages):
#Open current chain:
wordDict = np.load('markov_dict.npy', allow_pickle=True).item()
@@ -207,7 +203,7 @@ class Chatbot(commands.Cog):
messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None)
allMessages = []
for i in range(nrOfMessages):
msg = yield from anext(messageIterator)
msg = await anext(messageIterator)
allMessages.append(msg)
i = 0
@@ -248,18 +244,17 @@ class Chatbot(commands.Cog):
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def reageer(self, ctx):
async def reageer(self, ctx):
"""Laat Stroop ergens op reageren.
Stroop leert van onze gesprekken. Hij kan zich nu voordoen als een van ons. Soort van.
"""
#Get previous message to respond to
messageIterator = ctx.channel.history(limit=3, before=None, after=None, oldest_first=False, around=None)
messageToRespondTo = yield from anext(messageIterator) #this will be the !reageer command. skip
messageToRespondTo = yield from anext(messageIterator)
messageToRespondTo = await anext(messageIterator) #this will be the !reageer command. skip
messageToRespondTo = await anext(messageIterator)
if messageToRespondTo.content.strip()[0] == '!' or messageToRespondTo.author.bot: #another chance
messageToRespondTo = yield from anext(messageIterator) #but it's not a huge problem if he responds to himself
messageToRespondTo = await anext(messageIterator) #but it's not a huge problem if he responds to himself
if messageToRespondTo.content.strip()[0] == '!':
wordsToRespondTo = []
else:
@@ -268,12 +263,12 @@ class Chatbot(commands.Cog):
#Delete command
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
pass
response = self.getResponseForMessage(wordsToRespondTo)
yield from ctx.channel.send(response)
await ctx.channel.send(response)
# Calculate probabilities and pick a next word from a word pair dict:
# https://stackoverflow.com/questions/835092/python-dictionary-are-keys-and-values-always-the-same-order
@@ -285,12 +280,11 @@ class Chatbot(commands.Cog):
#Respond to a message.
#Assumes the message isn't a command
@asyncio.coroutine
def respondToMessage(self, message):
async def respondToMessage(self, message):
wordsToRespondTo = message.content.strip().split()
response = self.getResponseForMessage(wordsToRespondTo)
yield from message.channel.send(response)
await message.channel.send(response)
#Gets a response
def getResponseForMessage(self, wordsToRespondTo):
@@ -351,7 +345,7 @@ class Chatbot(commands.Cog):
chain[n] = "@jemoeder"
#print(' '.join(chain))
#yield from ctx.channel.send(' '.join(chain))
#await ctx.channel.send(' '.join(chain))
return ' '.join(chain)
@@ -424,22 +418,20 @@ class Chatbot(commands.Cog):
return ' '.join(chain)
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def haiku(self, ctx):
async def haiku(self, ctx):
"""Stroop is een poëet. Laat hem een Haiku maken.
"""
response = self.getHaiku()
yield from ctx.channel.send(response)
await ctx.channel.send(response)
@commands.command(pass_context=True, hidden=False)
@asyncio.coroutine
def uitspraak(self, ctx, numPosts=1):
async def uitspraak(self, ctx, numPosts=1):
"""Random uitspraak uit de hall of fame.
Optioneel kan je een nummer meegeven voor meerdere uitspraken
0 voor alle uitspraken."""
try:
yield from ctx.message.delete()
await ctx.message.delete()
except:
pass
try:
@@ -451,6 +443,6 @@ class Chatbot(commands.Cog):
numPosts = len(uitspraken)
for i in range(numPosts):
message += uitspraken[i]
yield from ctx.channel.send(message)
await ctx.channel.send(message)
except:
pass