Page MenuHomePhabricator (Chris)

No OneTemporary

Authored By
Unknown
Size
14 KB
Referenced Files
None
Subscribers
None
diff --git a/commandhandler.py b/commandhandler.py
index 57a42b2..72f5090 100644
--- a/commandhandler.py
+++ b/commandhandler.py
@@ -1,229 +1,175 @@
#This is the Command Handler file
#Handles all bot commands
import telepot
from telepot.namedtuple import *
import group_utilities
from random import randrange, random
import datetime
import tinydb
stfu_phrases = group_utilities.read_lines('stfu_phrases.txt')
response_phrases_y = (group_utilities.read_lines('response_phrases_y.txt'))
response_phrases_n = (group_utilities.read_lines('response_phrases_n.txt'))
beescript = group_utilities.read_lines('beescript.txt')
lemmesmashList = group_utilities.read_lines('lemmesmash.txt')
blacklist = tinydb.TinyDB('blacklist.json')
dbquery = tinydb.Query()
recentUsers = {} #Recent bot users, used for the cooldown
-commands = ['/beemovie', '/stfu', '/ask', '/roll', '/dab', '/nice', '/lemmesmash']
-# commands = {'/beemovie' : beemovie}
+
+
def lemmesmash(msg, chat_id, bot):
''' /lemmesmash
USAGE: /lemmesmash
RETURNS:
'''
phrase = lemmesmashList[randrange(len(lemmesmashList))] #find a phrase
bot.sendMessage(chat_id, phrase) #send the phrase
group_utilities.logger('command', msg, False, phrase, '/lemmes')
def dab(msg, chat_id, bot):
''' /dab
USAGE: /dab
- RETURNS: A terrible sticker of an emoji doing a dab
+ RETURNS: A terrible sticker of an emoji dabbing
'''
+
bot.sendSticker(chat_id, 'CAADBAADRwADpnjSCTlOo90rUVSNAg')
group_utilities.logger('command', msg, False, '*dabs*', '/dab')
+ try:
+ bot.deleteMessage((chat_id, msg['message_id']))
+ except:
+ print "I need message removal rights for {}!!".format(str(chat_id));
def nice(msg, chat_id, bot):
''' /nice
USAGE: /nice [quantity]
RETURNS: Random ammount of nices between 1-10 unless a quantity is provided (max 250)
'''
if (len(msg['text'].split(' '))) > 1:
try:
nices = int(msg['text'].split(' ')[1])
if nices > 250:
nices = 250
if nices == 0:
nices = randrange(0, 10)
except ValueError:
nices = randrange(0, 10)
else:
nices = randrange(0, 10)
bot.sendMessage(chat_id, "nice"*nices)
group_utilities.logger('command', msg, False, 'nice'*nices, '/nice')
def beemovie(msg, chat_id, bot):
''' /beemovie
USAGE: /beemovie [repalceword]
REUTURS: Three random lines from the bee movie script
If a [replaceword] has been passed it will spit three random lines containing the word bee, but it replaced with [replaceword]
'''
lines = [] # The final list containing the lines
output = '' #The final output that the bot reuturns to the chat_id
args = msg['text'].replace(msg['text'].split(' ')[0],'')[1:] #What is after /beemovie or /beemovie@Jannie_Bot
if args.isspace() or args == '': #Is the command being queried like this /beemovie
lineno = randrange(0, (len(beescript)-2)) #what line number to use from beescript.txt
[lines.append(beescript[lineno+i]) for i in range(0,3)] #find a line and 2 after
output = "\n".join(lines)
else: #Is the command being queryied like this /beemovie [phrase]
while True: #repeat until bee is found in the lines
lines = []
lineno = randrange(0, (len(beescript)-2)) #what line number to use from beescript.txt
[lines.append(beescript[lineno+i]) for i in range(0,3)] #find a line and 2 after
if any('bee' in s for s in lines): #if there is bee in the lines
break #kill the loop
output = "\n".join(lines).replace('bee', args).replace('Bee', args).replace('TOMTOMTOMTOM','been') #replace words with the arg passed. TOMTOMTOMTOM is there because it kept replacing stuff in been
bot.sendMessage(chat_id, output)
group_utilities.logger('command', msg, False, output, '/beemovie')
def stfu(msg, chat_id, bot):
''' /stfu
USAGE: /stfu
RETURNS: Replies with randomly selected phrase determined in stfu_phrases
'''
phrase = stfu_phrases[randrange(len(stfu_phrases))] #find a phrase
bot.sendMessage(chat_id, phrase) #send the phrase
group_utilities.logger('command', msg, False, phrase, '/stfu') #log it
def ask(msg, chat_id, bot):
''' /ask
USAGE: /ask [question]
RETURNS: Replies with randomly selected phrase determined in response_phrases_y and response_phrases_n
'''
if random() > 0.5:
phrase = response_phrases_y[randrange(len(response_phrases_y))]
else:
phrase = response_phrases_n[randrange(len(response_phrases_n))]
if (("/ask@Jannie_Bot" in msg['text']) and (len(msg['text']) > 15)): #Is there actually a quesiton for /ask@Jannie_Bot
bot.sendMessage(chat_id, phrase, reply_to_message_id=msg['message_id'])
elif (("/ask" in msg['text']) and (len(msg['text']) > 4)) and ("/ask@Jannie_Bot" != msg['text'][:len("/ask@Jannie_Bot")]): #Is there actually a question or is it just /ask@Jannie_Bot
bot.sendMessage(chat_id, phrase, reply_to_message_id=msg['message_id'])
else: #No question?
phrase = "Give me a question you Heretic"
bot.sendMessage(chat_id, phrase, reply_to_message_id=msg['message_id'])
group_utilities.logger('command', msg, False, phrase, '/ask')
def roll(msg, chat_id, bot):
''' /roll
USAGE: /roll
RETURNS: Replies with random 9 digit number then if there are trips, dubs, quads etc will also congratulate
'''
dubzreponses={
0: None,
1: "Nice dubz boi",
2: "You got trips fag, nice",
3: "Quadzz nigga",
4: "Fuck me those are pents",
5: "You got some sexes there boy",
6: "Holy fuck you just rolled for septs",
7: "Jesus christ on a dubzicle those are fucking octs",
8: "You have aquired the respect from Jan, with those ninefolds we can recolonise the whole Universe",
}
roll_list = []
roll = str(randrange(10**8, 10**9)) #generate the roll
bot.sendMessage(chat_id, roll, reply_to_message_id=msg['message_id'])
for i in roll: #basically this whole chunk detects if there are dubs trips etc
roll_list.append(i)
counter = 0
for i in range(0,8):
if roll_list[i] == roll_list[i+1]:
counter +=1
else:
counter = 0
try:
bot.sendMessage(chat_id,dubzreponses[counter])
group_utilities.logger('command', msg, False, str(roll)+" ("+dubzreponses[counter]+")", '/roll')
except:
group_utilities.logger('command', msg, False, str(roll), '/roll')
pass
def config(msg, chat_id, bot): #WORK IN PROGRESS
#bot.sendMessage(chat_id, "Awe Lets Test?", reply_markup=ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='yes'), KeyboardButton(text='no')]]))
bot.sendMessage(chat_id, "Awe Lets Test?", reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text='yes', callback_data='yeee'), InlineKeyboardButton(text='no', callback_data='nein')]]))
def rotfl(msg, chat_id, bot):
''' /rotfl
USAGE: /rotfl (text)
RETURNS: rOfTL caT
'''
if "/rotfl@Jannie_Bot" in msg['text']:
TEMPVAR = msg['text'].split('/rotfl@Jannie_Bot')[1]
else:
TEMPVAR = msg['text'].split('/rotfl')[1]
out = ''
out = out.join([chr(ord(x)-32) if random() > 0.5 and x.isalpha() and x.islower() and x else x for x in TEMPVAR])
bot.sendMessage(chat_id, out)
-
-
-def handler(msg, cooldown_sec, bot):
- content_type, chat_type, chat_id = telepot.glance(msg)
-
- if not msg['from']['id'] in recentUsers: #Is the person in the recent users dict
-
- if blacklist.search(dbquery.id == msg['from']['id']) != []:#Is the person in the blacklist
- group_utilities.logger('blacklist', msg, False, 0, 0)
- return
-
- elif not msg['from']['username'] == 'profhiggins': #If the person isn't profhiggins, save the time the message was sent
- recentUsers[msg['from']['id']] = datetime.datetime.now()
-
- else: #If the person IS in the recent users dict
- if blacklist.search(dbquery.id == msg['from']['id']) != []:#Is the person in the blacklist?
- group_utilities.logger('blacklist', msg, False, 0, 0)
- return
-
- elif (datetime.datetime.now() - recentUsers[msg['from']['id']]) > datetime.timedelta(0, cooldown_sec): #Was the the timestamp in the dictionary more than cooldown_sec ago
- del recentUsers[msg['from']['id']] #Remvoe the listing in the dict
- recentUsers[msg['from']['id']] = datetime.datetime.now() #Put this message in the dictionary
-
- else: #Was the message sent less than cooldown_sec ago?
- group_utilities.logger('cooldown', msg, False, str(datetime.datetime.now() - recentUsers[msg['from']['id']]), 0)
- return
-
- #what command gets handled where
- if msg['text'][:len('/stfu')] == '/stfu':
- stfu(msg, chat_id, bot)
-
- if msg['text'][:len('/ask')] == '/ask':
- ask(msg, chat_id, bot)
-
- if msg['text'][:len('/roll')] == '/roll':
- roll(msg, chat_id, bot)
-
- if msg['text'][:len('/config')] == '/config':
- config(msg, chat_id, bot)
-
- if msg['text'][:len('/beemovie')] == '/beemovie':
- while 1: #some unicode error keeps popping up and I don't have the effort to fix that, keep retrying till it works
- try:
- beemovie(msg, chat_id, bot)
- break
- except:
- pass
-
- if msg['text'][:len('/nice')] == '/nice':
- nice(msg, chat_id, bot)
-
- if msg['text'][:len('/dab')] == '/dab':
- dab(msg, chat_id, bot)
-
- if msg['text'][:len('/lemmesmash')] == '/lemmesmash':
- lemmesmash(msg, chat_id, bot)
-
- if msg['text'][:len('/rotfl')] =='/rotfl':
- rotfl(msg, chat_id, bot)
diff --git a/main.py b/main.py
index 0bb90f2..8416320 100644
--- a/main.py
+++ b/main.py
@@ -1,69 +1,96 @@
import sys
import time
import telepot
import datetime
-import commandhandler
+from commandhandler import *
import group_utilities
import random
#Cooldown length in seconds
COOLDOWN_SEC = 10
#fetching our BOT_TOKEN
-# BOT_TOKEN = sys.argv[1]
-BOT_TOKEN = "258778063:AAG9TaTSvo7mxiVwGl_lxqiPSLYy6eFe97Q"
+BOT_TOKEN = sys.argv[1]
+
+
+commands = {
+ '/stfu' : stfu,
+ '/ask' : ask,
+ '/roll' : roll,
+ '/beemovie' : beemovie,
+ '/nice' : nice,
+ '/dab' : dab,
+ '/lemmesmash' : lemmesmash,
+ '/rotfl' : rotfl
+}
def chat_handler(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
if content_type == 'text':
#If the message contains a bot command, go tell command_handler
try:
if msg['entities'][0]['type'] == 'bot_command':
- commandhandler.handler(msg, COOLDOWN_SEC, bot)
+ handler(msg, COOLDOWN_SEC, bot)
#If the message contains Hendrik, send a complaint message to sender
except KeyError:
- #if "hendrik" in (msg['text'].lower()):
- # bot.sendMessage(chat_id, 'THAT WITCH NAME IS NOT TO BE SPOKEN!', reply_to_message_id=msg['message_id'])
- # group_utilities.logger('hendrik', msg, False, 0, 0)
-
if ' lumber' in (msg['text'].lower()) or 'lumber' == msg['text'].lower()[:len('lumber')]:
if random.randint(0,1) == 1:
bot.sendMessage(chat_id, "LUMBER IS ETERNAL")
else:
bot.sendMessage(chat_id, 'THERE ARE NO BRAKES ON THE LUMBER TRAIN')
- # if ' apple' in (msg['text'].lower()) or 'apple' == msg['text'].lower()[:len('apple')]:
- # bot.sendMessage(chat_id, "FUCK APPLE")
- #
- # if 'kak dela' in (msg['text'].lower()):
- # bot.sendMessage(chat_id, "Harsho Spasiba", reply_to_message_id=msg['message_id'])
- #
- # if 'random = funny' in (msg['text'].lower()):
- # bot.sendMessage(chat_id, "Stop over using this", reply_to_message_id=msg['message_id'])
-
def edit_handler(msg):
content_type, chat_type, chat_id = telepot.glance(msg)
try:
if msg['entities'][0]['type'] == 'bot_command':
bot.sendMessage(chat_id, "Voetsek, don't edit your commands.", reply_to_message_id=msg['message_id'])
except:
if content_type == 'text':
pass
#if "hendrik" in (msg['text'].lower()):
# bot.sendMessage(chat_id, 'THAT WITCH NAME IS NOT TO BE SPOKEN! DO NOT TRY EDIT YOUR WITCHCRAFT INTO YOUR MESSAGES IN AN ATTEMPT TO EVADE ME!', reply_to_message_id=msg['message_id'])
# group_utilities.logger('hendrik', msg, True, 0, 0)
def callback_query_handler(msg):
pass
-#make our bot and feed it the tokenhend
-bot = telepot.Bot(BOT_TOKEN)
+def handler(msg, cooldown_sec, bot):
+ content_type, chat_type, chat_id = telepot.glance(msg)
+ tempcommand = None
+ if not msg['from']['id'] in recentUsers: #Is the person in the recent users dict
+
+ if blacklist.search(dbquery.id == msg['from']['id']) != []:#Is the person in the blacklist
+ group_utilities.logger('blacklist', msg, False, 0, 0)
+ return
+
+ elif not msg['from']['username'] == 'profhiggins': #If the person isn't profhiggins, save the time the message was sent
+ recentUsers[msg['from']['id']] = datetime.datetime.now()
+
+ else: #If the person IS in the recent users dict
+ if blacklist.search(dbquery.id == msg['from']['id']) != []:#Is the person in the blacklist?
+ group_utilities.logger('blacklist', msg, False, 0, 0)
+ return
+
+ elif (datetime.datetime.now() - recentUsers[msg['from']['id']]) > datetime.timedelta(0, cooldown_sec): #Was the the timestamp in the dictionary more than cooldown_sec ago
+ del recentUsers[msg['from']['id']] #Remvoe the listing in the dict
+ recentUsers[msg['from']['id']] = datetime.datetime.now() #Put this message in the dictionary
+
+ else: #Was the message sent less than cooldown_sec ago?
+ group_utilities.logger('cooldown', msg, False, str(datetime.datetime.now() - recentUsers[msg['from']['id']]), 0)
+ return
+
+ for command in commands:
+ if msg['text'][:len(command)] == command:
+ commands[command](msg, chat_id, bot)
+
+if __name__ == '__main__':
+ #make our bot and feed it the tokenhend
+ bot = telepot.Bot(BOT_TOKEN)
-#fetch messages and keep script looped
-while 1:
+ #fetch messages and keep script looped
bot.message_loop({'chat' : chat_handler,
'edited_chat' : edit_handler,
'callback_query' : callback_query_handler},
run_forever="Bot Running...")

File Metadata

Mime Type
text/x-diff
Expires
Wed, Jun 17, 9:20 PM (1 w, 5 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
72135
Default Alt Text
(14 KB)

Event Timeline