Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- subscribers - tier 1 1000, tier 2 2500 tier 3 5000 / semaine
- DONE !gamble X : d100 50 -> x/2 gagnés
- !versus
- !contest
- DONE !makeitrain
- DONE !doubletrouble
- DONE !kekettes pour voir les kekettes
- cheer = 1000 points par 100 bits
- !addquote
- !quotelist
- pseudo 1: !vs "pseudo2" "montant"
- bot: pseudo2 vous êtes challengé par "pseudo1"
- pseudo2: !vs pseudo1 "montant"
- plus on parie plus on a de chances de gagner base montant1=montant2 : 50/50
- montant1/(montant1+2)*100 %
- """
- import socket
- import twitch
- from twitch import TwitchClient
- from twitch.api.streams import Streams
- import csv
- from datetime import datetime
- import time
- from threading import Thread, RLock
- import random as rd
- import math
- lock = RLock()
- BOT_HAS_STARTED = "KekettesBot is now running !"
- NOT_ENOUGH_POINTS = "User {} has not enough kekettes to perform this action."
- DISPLAY_POINTS = "User {} has {} kekettes"
- USER_CHALLENGED_YOU = "{0}, user {1} has challenged you ! Type !vs {1} *amount* to accept."
- DISPLAY_CHALLENGE_ODDS = "{0} has put {1} on the table. {2} has put {3} on the table. {0} has {4}% chances of winning !"
- VS_WIN = "You won your duel versus {0}, you win {} kekettes."
- VS_LOST = "You lost your duel versus {0}, you lose {} kekettes."
- GAMBLE_WON = "{} rolled {} and thus has won {} kekettes !"
- GAMBLE_LOST = "{} rolled {} and thus has lost {} kekettes !"
- VALUE_ERROR_EXCEPTION = "You entered an incorrect value."
- BOT_LEAVING_CHAT = "KekettesBot has left the chat room, goodbye!"
- MADE_IT_RAIN = "Woohoo, {} made it rain !"
- DOUBLE_TROUBLE_STARTED = "{} has requested double points ! Everyone gets double for 10 minutes !"
- DOUBLE_TROUBLE_ENDED = "Double trouble has ended !"
- HELP_MESSAGE = "Available Commands: {}"
- SOURCE_CODE_MESSAGE = "Here's the source code for this bot : <link>"
- QUOTES = []
- with open("quotes.txt", "r") as f:
- for line in f:
- QUOTES.append(line.rstrip("\n"))
- next_call = time.time()
- def sourcecode(users, text, user):
- return
- def quote(users, text, user):
- return rd.choice(QUOTES), users
- def denisbrogniart(users, text, user):
- return "HA !", users
- def helpkekettes(users, text, user):
- return HELP_MESSAGE, users
- def kekettes(users, text, user):
- return DISPLAY_POINTS.format(user.username.capitalize(), user.current), users
- pass
- def gamble(users, text, user):
- balance = user.current
- try:
- message = text.split(":")[-1]
- gmbl = message.split()[-1]
- gmbl = int(gmbl)
- except ValueError:
- return VALUE_ERROR_EXCEPTION, users
- if user.may_perform_action(gmbl):
- user.add_points(-gmbl)
- else:
- return NOT_ENOUGH_POINTS.format(user.username.capitalize()), users
- rng = rd.randint(1, 100)
- if rng <50:
- return GAMBLE_LOST.format(user.username.capitalize(), rng, gmbl), users
- else:
- winnings = gmbl*(math.ceil((rng-50)/50*4)+1)
- user.add_points(winnings)
- return GAMBLE_WON.format(user.username.capitalize(), rng, winnings-gmbl), users
- pass
- def doubletrouble(users, text, user):
- username = username = text.split(":")[1].split("!")[0]
- now = datetime.now().time()
- then = addSecs(now, 600)
- if user.may_perform_action(2000):
- user.add_points(-2000)
- else:
- return NOT_ENOUGH_POINTS.format(user.username.capitalize()), users
- return (then, DOUBLE_TROUBLE_STARTED.format(user.username.capitalize())), users
- pass
- def versus(users, text, user):
- pass
- def makeitrain(users, text, user):
- if user.may_perform_action(3000):
- user.add_points(-3000)
- else:
- return NOT_ENOUGH_POINTS.format(user.username.capitalize()), users
- for u in users:
- u.add_points(30)
- return MADE_IT_RAIN.format(user.username.capitalize()), users
- pass
- def addSecs(tm, secs):
- fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)
- fulldate = fulldate + datetime.timedelta(seconds=secs)
- return fulldate.time()
- class User():
- def __init__(self, row):
- self.fieldnames = ['username', 'user_id', 'current', 'all_time']
- self.row = row
- self._username = row["username"]
- self._user_id = int(row["user_id"])
- self._current = int(row["current"])
- self._all_time = int(row['all_time'])
- def _get_username(self):
- return self._username
- def _set_username(self, new_username):
- self._username = str(new_username)
- def _get_user_id(self):
- return self._user_id
- def _set_user_id(self, id_):
- self._user_id = id_
- def _get_current(self):
- return self._current
- def _set_current(self, new_current):
- delta = int(self._all_time) - int(new_current)
- if delta >0:
- self._all_time = int(self._all_time) + int(delta)
- self._current = int(new_current)
- def _get_all_time(self):
- return int(self._all_time)
- def _set_all_time(self, new_all_time):
- self._all_time = int(new_all_time)
- username = property(_get_username, _set_username)
- user_id = property(_get_user_id, _set_user_id)
- current = property(_get_current, _set_current)
- all_time = property(_get_all_time, _set_all_time)
- def add_points(self, points_to_add):
- self.current += points_to_add
- def may_perform_action(self, cost):
- return self.current-cost >=0
- def __repr__(self):
- return "{}:{}, {}/{}".format(self.username, self.user_id, self.current, self.all_time)
- class KeketteBot(Thread):
- def __init__(self, commands):
- Thread.__init__(self)
- self.stop = False
- #CONFIG
- self.channel_name = 'misterteamot'
- self.channel_oauth = '<redacted>' #teamot oauth
- self.max_messages = 100 #/30 sec
- self.max_joins = 50 #/15 sec
- self.base_drop_rate = 2 #per minute
- self.points_multiplier = 1
- self.csv_filename = "points.csv"
- #IRC CONFIG
- self.server = 'irc.chat.twitch.tv'
- self.port = 6667
- self.nickname = 'kekettesbot'
- self.password = '<redacted>' #oauth token for the bot
- self.commands = commands
- self.given_to_subs = False
- self.end_doubletrouble = datetime.now().time()
- self.doubletroublechanged = False
- self.time_start_daemon = time.time()
- self.points_not_given = True
- self.joined_users = []
- #Loader for csv data
- fields = ['username', 'user_id', 'current', 'all_time']
- #self.users = {'username':[], 'user_id':[], 'current':[], 'all_time':[]}
- self.users = []
- with open(self.csv_filename, "r") as csvfile:
- reader = csv.DictReader(csvfile, fieldnames=fields)
- i = 0
- for row in reader:
- i+=1
- if i>1:
- self.users.append(User(row))
- #for f in fields:
- # self.users[f].append(row[f])
- print(self.users)
- #IRC STUFF
- self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #defines the socket
- # Connect
- #self.irc.bind((self.server, self.port))
- self.irc.connect((self.server, self.port))
- self.irc.setblocking(False)
- self.irc.send("PASS {}\n".format(self.password).encode())
- self.irc.send("NICK {}\n".format(self.nickname).encode())
- self.irc.send("JOIN #{}\n".format(self.channel_name).encode())
- self.irc.send("PRIVMSG #{} :{}\n".format(self.channel_name, BOT_HAS_STARTED).encode())
- self.irc.send("CAP REQ :twitch.tv/membership\n".encode())
- self.irc.send("CAP REQ :twitch.tv/tags\n".encode())
- #TWITCH API STUFF
- self.client_id = 'iaqh3hzv031qgn4182ardxfaeqiyzt'
- self.client = TwitchClient(self.client_id, self.channel_oauth)
- #self.channel = self.client.channels.get()
- current_offset = 0
- self.subscribers = []
- self.subscribers_twitch = []
- #while self.client.channels.get_subscribers(self.channel._id, limit=100, offset=current_offset):
- # self.subscribers.extend(self.client.channels.get_subscribers(self.channel_oauth, limit=100, offset=current_offset))
- # current_offset += 100
- def run(self):
- while not self.stop:
- with lock:
- if datetime.now().time() > self.end_doubletrouble and self.doubletroublechanged:
- self.points_multiplier = 1
- self.irc.send('PRIVMSG #{} :{}\n'.format(self.channel_name, DOUBLE_TROUBLE_ENDED).encode())
- self.doubletroublechanged = False
- if int(time.time()-self.time_start_daemon)%120==0 and self.points_not_given:#datetime.now().minute%2 == 0 and datetime.now().second == 1: #donne des kekettes toutes les 2 minutes
- self.points_not_given = False
- for user in self.joined_users: #TODO: les viewers qui n'ont pas encore de kekettes (les nouveaux)
- user.add_points(self.base_drop_rate*self.points_multiplier)
- """index = self.users["user_id"].index(self.joined_users[i][1])
- current = self.users["current"][index]
- current = int(current)
- current += self.base_drop_rate * self.points_multiplier
- self.users["current"][index] = str(current)"""
- if not self.points_not_given and int(time.time()-self.time_start_daemon)%121==0:
- self.points_not_given = True
- if datetime.now().weekday() == 0 and not self.given_to_subs: #Monday #Donne 1000 kekettes aux subs par semaine
- self.given_to_subs = True
- for sub in self.subscribers:
- sub.add_points(1000)
- #i = self.users["user_id"].index(str(sub.id_))
- #self.users["current"][i] += 1000
- try:
- text=self.irc.recv(4096).decode()
- print(text)
- # Prevent Timeout
- if text.find('PING') != -1:
- self.irc.send('PONG {}\r\n'.format(text.split()[1]).encode())
- print('PONG {}\r\n'.format(text.split()[1]))
- elif text.find("JOIN") != -1:
- username = text[:1].split("!")[0]
- user_id = str(self.client.users.translate_usernames_to_ids(list(username))[0])
- #self.joined_users.append((username, user_id))
- if user_id not in [x.user_id for x in self.users]:
- row={'username':username, 'user_id':user_id, 'current':0, 'all_time':0}
- self.users.append(User(row))
- self.joined_users.append(self.users[-1])
- else:
- i = [x.user_id for x in self.users].index(user_id)
- self.joined_users.append(self.users[i])
- #self.users['user_id'].append(user_id)
- #self.users['current'].append('0')
- #self.users['all_time'].append('0')
- #If message received
- elif text.find('PRIVMSG') != -1:
- if "!quit" in text and "mod" in text.split("user-type=")[1].split(":")[0]:
- self.quit()
- for command, handle in self.commands.items():
- if text.find(command) != -1:
- print("Command found !")
- username = text.split(":")[1].split("!")[0]
- user_id = text.split("user-id=")[1].split(";")[0]
- index = [x.user_id for x in self.users].index(int(user_id))
- user = self.users[index]
- print((username, user_id))
- output, self.users = handle(self.users, text, user)
- print(output)
- if type(output) == type(str()):
- self.irc.send('PRIVMSG #{} :{}\n'.format(self.channel_name, output).encode())
- elif type(output) == type(tuple()):
- self.points_multiplier += 1
- self.end_doubletrouble = output[0]
- self.doubletroublechanged = True
- self.irc.send('PRIVMSG #{} :{}\n'.format(self.channel_name, output[1]).encode())
- except Exception as e:
- if "10035" not in repr(e):
- print("{} : {}".format(type(e), e))
- continue
- def quit(self):
- self.irc.send('PRIVMSG #{} :{}\n'.format(self.channel_name, BOT_LEAVING_CHAT).encode())
- self.irc.send('PART'.encode())
- self.irc.close()
- self.stop = True
- with open(self.csv_filename, 'w') as csvfile:
- fieldnames = ['username', 'user_id', 'current', 'all_time']
- writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
- writer.writeheader()
- for i in range(len(self.users['username'])):
- writer.writerow({
- 'username': self.users["username"][i],
- 'user_id': self.users["user_id"][i],
- 'current': self.users["current"][i],
- 'all_time': self.users["all_time"][i]
- })
- def main():
- commands = {'!kekettes':kekettes, #displays the amount of points the user has
- '!gamble':gamble, #gamble a set amount of points
- '!makeitrain':makeitrain, #gives each user 30 points
- '!doubletrouble':doubletrouble, #double the drop-rate of points for 30 minutes
- '!versus':versus, # challenge un autre viewer a un versus
- '!helpkekettes':helpkekettes, #Affiche l'aide
- '!quote':quote, #affiche une quote de teamot
- '!denisbrogniart': denisbrogniart #AH !
- }
- cmds = [str(k) for k in commands.keys()]
- cmd_str = ""
- for i in cmds:
- cmd_str += i+", "
- cmd_str.rstrip(", ")
- print(cmd_str)
- HELP_MESSAGE.format(cmd_str)
- #Most normal chat commands like /timeout, /ban, /clear are sent with periods
- #in place of the forward slash. For example, to ban the user "xangold", you
- #would send ".ban xangold" to the server (minus the quotes).
- bot = KeketteBot(commands)
- print('KekettesBot is now running !')
- bot.start()
- if __name__ == '__main__':
- main()
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement