diff --git a/Chatbot.py b/Chatbot.py index 2d7b879..c00c604 100644 --- a/Chatbot.py +++ b/Chatbot.py @@ -6,7 +6,7 @@ import random from datetime import datetime import re -class Chatbot(object): +class Chatbot(commands.Cog): """Een heuse chatbot. Under construction...""" def __init__(self, bot): @@ -17,7 +17,7 @@ class Chatbot(object): self.pmLast = datetime(2018, 1, 1, 1, 1, 1) self.pmCount = 0 try: - np.load('markov_dict.npy') + np.load('markov_dict.npy', allow_pickle=True) except FileNotFoundError: #If there's no initial file, make a new one: initFile = {'pairs':{self.START_OF_MESSAGE:{'Hoi':1},'Hoi':{self.END_OF_MESSAGE:1}}, 'trairs':{}, 'responsePairs':{}} @@ -187,10 +187,10 @@ class Chatbot(object): channel=self.bot.get_channel(channelId) #Open current chain: - wordDict = np.load('markov_dict.npy').item() + wordDict = np.load('markov_dict.npy', allow_pickle=True).item() #Iterate through the last x messages from the channel: - messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, reverse=False, around=None) + messageIterator = channel.history(limit=nrOfMessages, before=None, after=None, oldest_first=False, around=None) allMessages = [] for i in range(nrOfMessages): msg = yield from messageIterator.next() @@ -241,7 +241,7 @@ class Chatbot(object): """ #Get previous message to respond to - messageIterator = ctx.channel.history(limit=3, before=None, after=None, reverse=False, around=None) + messageIterator = ctx.channel.history(limit=3, before=None, after=None, oldest_first=False, around=None) messageToRespondTo = yield from messageIterator.next() #this will be the !reageer command. skip messageToRespondTo = yield from messageIterator.next() if messageToRespondTo.content.strip()[0] == '!' or messageToRespondTo.author.bot: #another chance @@ -276,7 +276,7 @@ class Chatbot(object): MAX_N_WORDS = 100 #Don't use more words than this #Get dictionary/Markov chain - wordDict = np.load('markov_dict.npy').item() + wordDict = np.load('markov_dict.npy', allow_pickle=True).item() wordPairDict = wordDict['pairs'] wordTrairDict = wordDict['trairs'] responsePairDict = wordDict['responsePairs'] @@ -389,7 +389,7 @@ class Chatbot(object): MAX_N_TRIES = 50 #Get dictionary/Markov chain - wordDict = np.load('markov_dict.npy').item() + wordDict = np.load('markov_dict.npy', allow_pickle=True).item() wordPairDict = wordDict['pairs'] #try: @@ -439,4 +439,4 @@ class Chatbot(object): message += uitspraken[i] yield from ctx.channel.send(message) except: - pass \ No newline at end of file + pass diff --git a/Cryptocoin.py b/Cryptocoin.py index 4b8e4e8..ba66b56 100644 --- a/Cryptocoin.py +++ b/Cryptocoin.py @@ -7,7 +7,7 @@ import time import random import statistics -class Cryptocoin(object): +class Cryptocoin(commands.Cog): """Voor al uw crypto currency advies.""" def __init__(self, bot): diff --git a/General.py b/General.py index 88567bf..3f8f06d 100644 --- a/General.py +++ b/General.py @@ -9,7 +9,7 @@ from sympy import latex, symbols, preview, Symbol #for LaTeX images import youtube_dl import ffmpeg -class General(object): +class General(commands.Cog): """Overal toegestaan.""" def __init__(self, bot): diff --git a/Points.py b/Points.py index c4d8a42..3bbe5a1 100644 --- a/Points.py +++ b/Points.py @@ -7,7 +7,7 @@ import numpy as np import random from datetime import datetime -class Points(object): +class Points(commands.Cog): """Geef elkaar punten!""" def __init__(self, bot): @@ -122,7 +122,7 @@ class Points(object): """ message = "**De puntentelling:** \n```" - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() pointsCountSorted = sorted(pointsCount.items(), key=lambda i: i[1]['points'], reverse=True) for user in pointsCountSorted: if user[0] != self.BANK_ID: @@ -146,31 +146,31 @@ class Points(object): # Transfer points form one user to another def transferPoints(self, fromUserId, toUserId, points): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() pointsCount[fromUserId]["points"] -= points pointsCount[toUserId]["points"] += points np.save("pointscount.npy", pointsCount) # Do we know this user? def isUserOnList(self, user): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() return user.id in pointsCount.keys() # Get a user's point balance def getUserBalance(self, user): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() return pointsCount[user.id]["points"] # Get the balance of the bank def getBankBalance(self): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() return pointsCount[self.BANK_ID]["points"] # To keep track if a user used some points today, we look at when the last time was he/she used them # If this was in the past: reset # Also, return the updated object. Why not. def refreshDateVarsAndReturnUserVars(self, userId): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() currentDateStr = datetime.now().strftime("%Y%m%d") if pointsCount[userId]["theDate"] != currentDateStr: pointsCount[userId]["theDate"] = currentDateStr @@ -192,14 +192,14 @@ class Points(object): # Increase the number of points this user has taken away today. # Warning: assumes you executed refreshDateVarsAndReturnUserVars() def increaseUsersPointTakenOnDate(self, userId, points): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() pointsCount[userId]["pointTakenOnDate"] += points np.save("pointscount.npy", pointsCount) # Increase the number of bank points this user has given today # Warning: assumes you executed refreshDateVarsAndReturnUserVars() def increaseUsersBankPointGivenAwayToday(self, userId, points): - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() pointsCount[userId]["bankPointsGivenOnDate"] += points np.save("pointscount.npy", pointsCount) @@ -252,10 +252,10 @@ class Points(object): def init(self): # Check if points file exists: try: - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() except FileNotFoundError: np.save("pointscount.npy", {}) - pointsCount = np.load('pointscount.npy').item() + pointsCount = np.load('pointscount.npy', allow_pickle=True).item() # Initialise the bank: if self.BANK_ID not in pointsCount.keys(): diff --git a/Shitpost.py b/Shitpost.py index a42ac41..d831852 100644 --- a/Shitpost.py +++ b/Shitpost.py @@ -3,7 +3,6 @@ import discord from discord.ext import commands from urllib import request import requests -import oauth2 as oauth import json, requests import math from datetime import datetime @@ -11,7 +10,7 @@ import sys import os import random -class Shitpost(object): +class Shitpost(commands.Cog): """Schijtpaal commando's. Alleen bruikbaar in de daarvoor toegewezen schijtpaal kanalen.""" def __init__(self, bot): diff --git a/Spotify.py b/Spotify.py deleted file mode 100644 index 5077104..0000000 --- a/Spotify.py +++ /dev/null @@ -1,126 +0,0 @@ -import discord -from discord.ext import commands -from discord.ext.commands import Bot -import json -import spotipy -import spotipy.util as util -from spotipy.oauth2 import SpotifyClientCredentials -import asyncio -import random -import time -from json.decoder import JSONDecodeError - -class Spotify(object): - """HD Con 2019 Playlist features! Alleen te gebruiken in het juiste kanaal""" - def __init__(self, bot): - self.bot = bot - - #voting settings - self.desired_count = 5 # aantal upvotes dat nodig is om een liedje in de lijst te krijgen - self.veto_count = 5 # aantal downvotes dat nodig is om een liedje weg te stemmen - self.thumbs_up = '👌' #"\N{Ok Hand Sign}" - self.thumbs_down = '🙅' #"\N{Face With No Good Gesture}" - self.stemkanaal_naam = 'top2000' # naam van het stemkanaal - - #All the spotipy settings - self.redirect = 'http://localhost' #must match app settings. - self.scope = 'user-read-private user-read-playback-state user-modify-playback-state playlist-modify-public playlist-modify-private' - self.username = self.bot.tokens["spotifyUsername"] - self.secret = self.bot.tokens["spotifySecret"] - self.client = self.bot.tokens["spotifyId"] - self.playlist_id = self.bot.tokens["spotifyPlaylist"] - - #Create spotipy objects for authentication - client_credentials_manager = SpotifyClientCredentials( - client_id=self.client, - client_secret=self.secret) - self.token = util.prompt_for_user_token( - username=self.username, - scope=self.scope, - client_id=self.client, - client_secret=self.secret, - redirect_uri=self.redirect) - self.sp_app = spotipy.Spotify(client_credentials_manager=client_credentials_manager) - self.sp_user = spotipy.Spotify(auth=self.token) - @self.bot.event - @asyncio.coroutine - def on_reaction_add(reaction, user): - # Als kanaal niet top2000 is niet tellen - if not reaction.message.channel.name.startswith(self.stemkanaal_naam): - return - # Bij genoeg stemmen voor - if reaction.emoji == self.thumbs_up and reaction.count >= self.desired_count: - print(str(reaction.message.content)) # debugging - with open("lijst.txt", "a") as f: - f.write(str(reaction.message.content)+'\n') - yield from reaction.message.delete() # verwijder poll - yield from reaction.message.channel.send("Dit nummer heeft genoeg stemmen ontvangen en is op de lijst gezet: " + str(reaction.message.content)) - try: - self.nummer_toevoegen(str(reaction.message.content)) - except: - pass - # Bij genoeg stemmen tegen - elif reaction.emoji == self.thumbs_down and reaction.count >= self.veto_count: - stemmen = reaction.message.reactions[0].count - 1 # tel het aantal voor-stemmen - if stemmen == 1: men = '' # om de grammar nazi's een plezier te doen - else: men = 'men' - yield from reaction.message.channel.send("Helaas, dit nummer heeft het ondanks " + str(stemmen) + " stem" + men + " niet gehaald: " + str(reaction.message.content)) - try: - yield from ctx.message.delete() - except: - pass - - #Properties and helper functions - @property - def playlist(self): - playlist_results = self.sp_user.user_playlist(self.username, self.playlist_id) - playlist_results = playlist_results['tracks']['items'] - return playlist_results - - def nummer_toevoegen(self, nummer): - tracks = ["spotify:track:"+nummer[31:]] # Het moet in een list - self.sp_user.user_playlist_add_tracks(user=self.username, playlist_id=self.playlist_id, tracks=tracks) - - #User-facing commands - @commands.command(pass_context=True, hidden=False) - @asyncio.coroutine - def geefplaylist(self, ctx): - yield from ctx.channel.send(ctx.author.mention + " https://open.spotify.com/playlist/" + self.playlist_id) - try: - yield from ctx.message.delete() - except: - pass - - @commands.command(pass_context=True, hidden=False) - @asyncio.coroutine - def nummers(self, ctx): - yield from ctx.channel.send(str(len(self.playlist))) - - @commands.command(pass_context=True, hidden=False) - @asyncio.coroutine - def stem(self, ctx, *, text=None): - '''Stel een liedje voor dat in de HDcon afspeellijst moet komen! De rest mag dan stemmen. - Werkt alleen in het #top2000 kanaal. - Bijvoorbeeld: - !stem https://open.spotify.com/track/LOr3miP5uMd0l0R51t4m3T''' - # Maak lijst met links om dubbele nummers te vermijden - voorlopigelijst = [line.rstrip('\n') for line in open('lijst.txt')] - # if not ctx.channel.id == stemkanaal: # ??? kapoet ??? - if not ctx.channel.name.startswith(self.stemkanaal_naam): # indien verkeerde kanaal - yield from ctx.channel.send(ctx.author.mention + ", stemmen doen we in het " + self.stemkanaal + " kanaal") - return - elif text in voorlopigelijst: # filter duplicaten - yield from ctx.channel.send(ctx.author.mention + ", je hebt geluk: dit liedje is reeds in de lijst opgenomen!") - return - if text != None and text.startswith("https://open.spotify.com/track/"): # indien geen leeg commando en valide link - message = yield from ctx.channel.send(text) - for emoji in (self.thumbs_up, self.thumbs_down): # geeft stemkeuze - yield from message.add_reaction(emoji) - else: - yield from ctx.channel.send(ctx.author.mention + ", je moet wel een valide link geven waar we op kunnen stemmen!") - try: - yield from ctx.message.delete() - except: - pass # pas op icm !stemtest - - diff --git a/Stroopwafel.py b/Stroopwafel.py index 5c07f7a..1086b15 100644 --- a/Stroopwafel.py +++ b/Stroopwafel.py @@ -6,7 +6,6 @@ import General import Cryptocoin import Chatbot import Points -import Spotify import logging import importlib import configparser @@ -42,7 +41,6 @@ bot.add_cog(Cryptocoin.Cryptocoin(bot)) bot.add_cog(Chatbot.Chatbot(bot)) pointsBot = Points.Points(bot) bot.add_cog(pointsBot) -bot.add_cog(Spotify.Spotify(bot)) @bot.event @asyncio.coroutine