def learntosing(link, db_connection): cursor = db_connection.cursor() # ~ if e['user_id'] in self.singbans: # ~ return helper.botMessage(message = "Ich hab Niveau!", _botname) link = link.replace('http://', 'https://').strip(_space_chars) link = link.replace('m.youtube.com', 'youtube.com') link = link.replace('youtu.be/', 'www.youtube.com/watch?v=') link = link.replace('&feature=youtu.be', '') if link.startswith('youtube') or link.startswith('www'): link = 'https://www.' + link if not linkRegex.match(link): return helper.botMessage("Die url passt nicht ganz.", _botname) query = cursor.execute( "SELECT id FROM songs WHERE link LIKE ?;", (re.sub(linkRegex, '\\1', link) + '%', ), ).fetchone() if query is not None: return helper.botMessage("Das kenn ich schon.", _botname) vid_id = link.partition("?v=")[2] vid_metadata = youtube.title(vid_id) if vid_metadata['status'] != 0: return helper.botMessage(vid_metadata['error'], _botname) vid_title = truncate(vid_metadata['title'], 50) cursor.execute("INSERT INTO songs (link) VALUES (?);", (link, )) db_connection.commit() return helper.botMessage('Ich kann jetzt was Neues singen: %s' % vid_title, _botname)
def get_poll_from_num(poll): if not poll.isnumeric(): return helper.botMessage("%s ist keine valide Pollnummer"%poll, _botname) res = Session().get(_url%poll) if not res.ok: return helper.botMessage("Ich kenne die Pollnummer %s nicht."%poll, _botname) soup = BeautifulSoup(res.text, features='html.parser') title = soup.find("h1", {"class": "with-tabs"}).getText() answers = [title,"\n"] polldiv = soup.find("div", {"class": "poll"}) if polldiv == None: return helper.botMessage("Die Nummer %s gehört zu keiner Umfrage."%poll, _botname) for i in polldiv.findAll("div", {"class": "text"}): opinion = i.getText().strip() votes = i.findNextSibling("div", {"class": "percent"}).getText().strip() answers.append(format_vote(opinion, votes)) answers.append(polldiv.find("div", {"class": "total"}).getText()) return helper.botMessage('\n'.join(answers), _botname)
def learntosing(link, db_connection): cursor = db_connection.cursor() # ~ if e['user_id'] in self.singbans: # ~ return helper.botMessage(message = "Ich hab Niveau!", _botname) link = link.replace('http://', 'https://').strip() if link.startswith('youtube'): link = 'https://www.' + link elif link.startswith('www.'): link = 'https://' + s link = link.replace('youtube.de', 'youtube.com') p = re.compile('^https:\/\/www.youtube.com\/watch\?v=[a-zA-Z0-9\-_]{,20}$') if not p.match(link): return helper.botMessage("Die url passt nicht ganz.", _botname) query = cursor.execute("SELECT id FROM songs WHERE link = ?;", (link, )).fetchone() if query is not None: return helper.botMessage("Das kenn ich schon.", _botname) # ~ vid = s.partition("?v=")[2] # ~ url = "https://www.googleapis.com/youtube/v3/videos?part=id&id=%s&key=%s" # ~ res = self.b.c.s.get(url%(vid,self.key)) # ~ resjson = json.loads(res.text) # ~ if resjson['items'] == []: # ~ return dict(name = str(self), message = "Ich glaube das Video gibts nicht") cursor.execute("INSERT INTO songs (link) VALUES (?);", (link, )) db_connection.commit() return helper.botMessage('Ich kann jetzt ' + link + ' singen.', _botname)
def removeasong(link, db_connection): cursor = db_connection.cursor() songid = cursor.execute('SELECT id FROM songs WHERE link == ?;', (link, )).fetchone() if songid is None: return helper.botMessage('Ich kenne %s nicht.' % link, _botname) cursor.execute('DELETE FROM songs WHERE id == ?;', (songid[0], )) db_connection.commit() return helper.botMessage('Ich kann jetzt %s nicht mehr singen.' % link, _botname)
def add_pollname(num, name, db_connection): if not num.isnumeric(): return helper.botMessage("%s ist keine valide Pollnummer."%(num), _botname) if name[0].isnumeric(): return helper.botMessage("Der Pollname darf nicht mit einer Zahl beginnen.", _botname) cursor = db_connection.cursor() dbnum = get_num_from_name(name, cursor) if dbnum is not None: return helper.botMessage("Der Pollname %s ist schon für %s vergeben."%(name, dbnum[0]), _botname) cursor.execute("INSERT INTO qedpoll(name, num) values(?,?)", (name, num)) db_connection.commit() return helper.botMessage("Die Poll %s hat nun den Namen %s."%(num, name), _botname)
def processMessage(args, rawMessage, db_connection): return if len(args) < 1 or args[0].lower() != "!" + _bottrigger: return expr = stripFromBegin(rawMessage["message"], ["!" + _bottrigger]).strip(''.join(_space_chars)) ret = timeout.timed_run(calc.evaluate, [expr]) if isinstance(ret, Exception): return helper.botMessage("Ein Fehler trat auf: %s" % ret, _botname) elif ret is None: return helper.botMessage("Die Evaluierung dauerte zu lange.", _botname) else: return helper.botMessage("%s" % ret, _botname)
def interact(victim): global _victims v = victim.lower() if not v in _victims: addVictim(v) ran = np.random.random() index = np.argmax(_victims[v]["P"] >= ran) msg = _reactions[index] name = _victims[v]["carp_name"] # potentially useful variables dmg = np.random.randint(1, 5) return helper.botMessage(msg.format(**globals(), **locals()), name)
def processMessage(args, rawMessage, db_connection): parsedArgs = list(filter(lambda x: len(x) > 0, args)) if len(parsedArgs) < 1 or parsedArgs[0].lower() != "!" + _bottrigger: return cursor = db_connection.cursor() if len(parsedArgs) == 2: return get_poll(parsedArgs[1], db_connection) elif len(parsedArgs) == 3: return add_pollname(parsedArgs[1], parsedArgs[2], db_connection) else: return helper.botMessage(_help, _botname)
def processMessage(args, rawMessage, db_connection): targetOptions = [t for t in targets if norm(t) == norm(rawMessage["name"])] if not targetOptions: return # no target, no praise target = targetOptions[0] # unpack origin = targets[target]["origin"] lastTime = targets[target]["lastTime"] if lastTime and _waittime > datetime.now() - lastTime: return None # too often praise is not good if random() > _praiseChance: return None # too many praise is not good targets[target]["lastTime"] = lastTime = datetime.now() return helper.botMessage("praise the %s \o/" % target, origin) # praise the fbot \o/
def processMessage(args, rawMessage, db_connection): global _last if len(args) < 1 or args[0].lower() != "!" + _bottrigger: # remember a person now = rawMessage["name"].strip(_space_chars) if now != _last[0]: _last = [now, _last[0]] return if len(args) < 2: now = rawMessage["name"].strip(_space_chars) if now != _last[0]: target = _last[0] # prev person else: target = _last[1] # prevprev person else: target = args[1].strip(_space_chars) # a specified person return helper.botMessage(f'praise the {target} \o/', _botname) # praise the fbot \o/
def processMessage(args, rawMessage, db_connection): if len(args) < 2: return if '' in args[:2]: return if args[0][0] not in ['#'] and args[0].lower() not in _unfreie_punkte: return parser = argparse.ArgumentParser() parser.add_argument('punktName', metavar='Punkt') parser.add_argument('username', metavar='Nick', nargs='?', default='self') parser.add_argument('-s', dest='toAdd', action='store_const', const=0) group = parser.add_mutually_exclusive_group() group.add_argument('-a', dest='toAdd', nargs='?', type=int, default=+1) group.add_argument('-r', dest='toAdd', nargs='?', type=negative_int, const=-1) try: parsedArgs = vars( parser.parse_known_args([x if x != '--' else '-r' for x in args])[0]) except argparse.ArgumentError: return helper.botMessage(str.replace(parser.format_usage(), '\n', ''), _botname) if parsedArgs['toAdd'] == None: parsedArgs['toAdd'] = 1 cursor = db_connection.cursor() if parsedArgs['username'] in ['self', 'selbst']: username = norm(rawMessage['name']) else: username = parsedArgs['username'] userid = helper.useridFromUsername(cursor, username) if userid is None: return helper.botMessage('Ich kenne %s nicht.' % username, _botname) username = helper.usernameFromUserid(cursor, userid) punktid = punktidFromPunktName(cursor, args[0]) punktname = punktNameFromPunktid(cursor, punktid) if punktname == None: punktname = args[0] punktnameToDisplay = punktname[1:] anzahl = anzahlFromPunktidAndUserid(cursor, punktid, userid) if parsedArgs['toAdd'] == 0: if anzahl == None: anzahl = 0 return helper.botMessage( username + ' hat ' + str(anzahl) + ' ' + punktnameToDisplay + '.', punktnameToDisplay) else: if punktid is None: cursor.execute('INSERT INTO freiepunkteliste (name) VALUES (?);', (punktname, )) punktid = cursor.execute( 'SELECT id FROM freiepunkteliste WHERE name == ?;', (punktname, )).fetchone()[0] if anzahl is None: anzahl = parsedArgs['toAdd'] cursor.execute( 'INSERT INTO freiepunkte ' '(userid, freiepunkteid, anzahl) ' 'VALUES (?, ?, ?) ' ';', (userid, punktid, anzahl)) else: anzahl += parsedArgs['toAdd'] cursor.execute( 'UPDATE freiepunkte ' 'SET anzahl = ? ' 'WHERE freiepunkteid = ? ' 'AND userid = ? ' ';', (anzahl, punktid, userid)) db_connection.commit() return helper.botMessage( username + ' hat jetzt ' + str(anzahl) + ' ' + punktnameToDisplay + '.', punktnameToDisplay) return
def get_poll_from_name(poll, cursor): match = get_num_from_name(poll, cursor) if match is None: return helper.botMessage("Ich kenne Pollname %s nicht."%poll, _botname) else: return get_poll_from_num(match[0])
def processMessage(args, rawMessage, db_connection): if random.randrange(_randompost_one_over_probability) == 0: msg_obj = random.choice(_names) return helper.botMessage(msg_obj[0], msg_obj[1]) return
def processMessage(args, rawMessage, db_connection): if len(args) == 0: return if args[0].lower() not in ['!nickname', '!nicknames']: return if len(args) < 2: return helper.botMessage(_help, _botname) cursor = db_connection.cursor() if args[1].lower() in ['self', 'selbst']: args[1] = norm(rawMessage['name']) useridQuery = cursor.execute( 'SELECT userid ' 'FROM nicknames ' 'WHERE lower(nickname) == ? ' ';', (args[1].lower(), )).fetchone() if useridQuery is None: return helper.botMessage('Ich kenne ' + args[1] + ' nicht.', _botname) userid = useridQuery[0] username = cursor.execute( 'SELECT nickname ' 'FROM nicknames ' 'WHERE userid == ? ' 'AND deletable == 1' ';', (userid, )).fetchone()[0] # print nicknames if len(args) == 2: message = '' nicknamelist = [] for nickname in cursor.execute( 'SELECT nickname ' 'FROM nicknames ' 'WHERE userid == ? ' 'AND deletable == 0' ';', (userid, )): nicknamelist.append(nickname[0]) if len(nicknamelist) < 1: return helper.botMessage(username + ' hat keine nicknames.', _botname) message = username + ' hat die Nicknames:\n' for nickname in nicknamelist: message += nickname + '\n' # add or remove nicknames elif len(args) == 4: if args[3].lower() in ['self', 'selbst'] or args[3] == '-': return helper.botMessage( 'Der nickname ' + args[3] + ' ist reserviert.', _botname) if args[2] == '-a': # add nickname cursor = db_connection.cursor() ## todo braucht man das wirklich toAddCheck = cursor.execute( 'SELECT userid ' 'FROM nicknames ' 'WHERE lower(nickname) == ?' ';', (args[3].lower(), )).fetchone() if toAddCheck is not None: message = 'Der nickname ' + args[3] + ' existiert schon.' else: nickListLength = cursor.execute( 'SELECT COUNT(*) ' 'FROM nicknames ' 'WHERE userid = ?' ';', (userid, )).fetchone() if nickListLength[0] >= _max_nicks_pp: return helper.botMessage( username + ' hat schon ' + str(_max_nicks_pp) + ' nicknames.', _botname) cursor.execute( 'INSERT INTO nicknames (nickname, userid) VALUES (?, ?);', (args[3], userid)) db_connection.commit() return helper.botMessage( username + ' hat nun den Nickname ' + args[3] + '.', _botname) elif args[2] == '-r': # remove nickname toRemoveCheck = cursor.execute( 'SELECT userid ' 'FROM nicknames ' 'WHERE lower(nickname) == ? ' 'AND deletable == 0 ' ';', (args[3].lower(), )).fetchone() if toRemoveCheck is None: message = 'Ich kenne ' + args[3] + ' nicht.' else: cursor = db_connection.cursor() cursor.execute( 'DELETE FROM nicknames ' 'WHERE lower(nickname) == ?' ';', (args[3].lower(), )) db_connection.commit() return helper.botMessage( username + ' hat jetzt den nicknamen ' + args[3] + ' nicht mehr.', _botname) else: return helper.botMessage(_help, _botname) else: return helper.botMessage(_help, _botname) return helper.botMessage(message, _botname)
def processMessage(args, rawMessage, db_connection): if len(args) < 2: return None if args[0].lower() != '!' + _bottrigger.lower(): return if args[1] == 'ping': return helper.botMessage('Hallu', _botname) elif args[1].lower() == 'ud': if len(args) <= 2: return helper.botMessage(_help_ud, _botname) term = stripFromBegin(rawMessage['message'], args[0:2]) return helper.botMessage(ud.ud_parser(term), _botname) elif args[1].lower() == 'decide': if len(args) < 2: return antwort = '+' if ord( hashlib.sha1(( rawMessage['message'].encode() + b'tpraR4gin8XHk_t3bGHZTJ206qc9vyV7LlUMTf655LNJDKGciVXKRLijqGkHgkpW <= Manfreds schlimmstes Geheimnis' )).hexdigest()[0]) % 2 == 1 else '-' return helper.botMessage(antwort, _botname) elif args[1].lower().startswith('sing'): parser = argparse.ArgumentParser(prog='!rita sing') parser.add_argument('song', nargs='?') parser.add_argument('-l', '--learn', action='store_true', dest='learn') parser.add_argument('-a', '--add', action='store_true', dest='learn') parser.add_argument('-r', '--remove', action='store_true', dest='remove') parser.add_argument('-h', '--help', action='store_true') parser.add_argument('-c', '--count', action='store_true') parser.add_argument('-v', '--version', action='store_true') # needed try: parsedArgs = vars(parser.parse_known_args(args[2:])[0]) except argparse.ArgumentError: return helper.botMessage(parser.print_usage(), _botname) if (( parsedArgs['learn'] or parsedArgs['remove'] ) and parsedArgs['song'] == None) or \ parsedArgs['help']: return helper.botMessage(parser.format_usage().rstrip('\n'), _botname) elif parsedArgs['version']: return helper.botMessage( 'secret unlocked \o/ the first one calling w/ID gets some chocolate', _botmessage) if parsedArgs['learn']: return learntosing(parsedArgs['song'], db_connection) elif parsedArgs['remove']: if rawMessage['username'] in botMasters: return removeasong(parsedArgs['song'], db_connection) else: return helper.botMessage( 'DU bist nicht mein botmaster. ich bin gescheitert', _botname) elif parsedArgs['count']: return helper.botMessage( 'Ich kann schon %s Lieder singen :) *stolz*' % songCount(db_connection.cursor()), _botname) return helper.botMessage(singasong(db_connection.cursor()), _botname) elif args[1].lower() in [_slap_trigger, _featurerequest_trigger]: if len(args) == 2: return helper.botMessage('was meinst du?', _botname) target = stripFromBegin(rawMessage['message'], args[0:2]) if args[1] == _slap_trigger: return helper.botMessage( '%s schlägt %s' % (_botname.replace('Dr. Ritastein', 'Rita'), target), _botname) elif args[1] == _featurerequest_trigger: return helper.botMessage('Ich will %s' % target, _botname) else: return helper.botMessage(_help, _botname)
def processMessage(args, rawMessage, db_connection): if len(args) < 2: return None if args[0].lower() != '!' + _bottrigger.lower(): return if args[1] == 'ping': return helper.botMessage('Hallu', _botname) elif args[1].lower() == 'ud': if len(args) <= 2: return helper.botMessage(_help_ud, _botname) term = stripFromBegin(rawMessage['message'], args[0:2]) return helper.botMessage(ud.ud_parser(term), _botname) elif args[1].lower() == 'decide': if len(args) < 2: return antwort = '+' if ord( hashlib.sha1(( rawMessage['message'].encode() + b'tpraR4gin8XHk_t3bGHZTJ206qc9vyV7LlUMTf655LNJDKGciVXKRLijqGkHgkpW <= Manfreds schlimmstes Geheimnis' )).hexdigest()[0]) % 2 == 1 else '-' return helper.botMessage(antwort, _botname) elif args[1].lower() == 'sing': parser = argparse.ArgumentParser() parser.add_argument('song', nargs='?') parser.add_argument('-l', '--learn', action='store_true', dest='learn') parser.add_argument('-r', '--remove', action='store_true', dest='remove') try: parsedArgs = vars(parser.parse_args(args[2:])) except argparse.ArgumentError: return helper.botMessage(_help_sing, _botname) if (parsedArgs['learn'] or parsedArgs['remove']) and parsedArgs['song'] is None: return helper.botMessage(_help_sing, _botname) if parsedArgs['learn']: return learntosing(parsedArgs['song'], db_connection) elif parsedArgs['remove']: return helper.botMessage( removeasong(parsedArgs['song'], db_connection), _botname) return helper.botMessage(singasong(db_connection.cursor()), _botname) elif args[1].lower() in [_slap_trigger, _featurerequest_trigger]: if len(args) == 2: return helper.botMessage('was meinst du?', _botname) target = stripFromBegin(rawMessage['message'], args[0:2]) if args[1] == _slap_trigger: return helper.botMessage('%s schlägt %s' % (_botname, target), _botname) elif args[1] == _featurerequest_trigger: return helper.botMessage('Ich will %s' % target, _botname) else: return helper.botMessage(_help, _botname)
def processMessage(args, rawMessage, db_connection): message = rawMessage['message'].lower() name = rawMessage['name'].lower() if ('<3' in message) and (not 'hannah' in message) and ('ludwig' in name): return helper.botMessage(":(", _botname)
def processMessage(args, rawMessage, db_connection): cursor = db_connection.cursor() message = None if rawMessage['username'] != None: recipientNicks = [rawMessage['username'].lower()] else: recipientNicks = [rawMessage['name'].lower()] for nick in cursor.execute( 'SELECT lower(nickname) ' 'FROM nicknames ' 'WHERE userid = (' 'SELECT userid ' 'FROM nicknames ' 'WHERE lower(nickname) == ? ' 'ORDER BY deletable DESC' ');', (recipientNicks[0], )): if nick[0].lower() not in recipientNicks: recipientNicks.append(nick[0].lower()) pingProperties = dict(print=True, delete=True) for nick in recipientNicks: cursor = db_connection.cursor() pongs = cursor.execute( 'SELECT sender, message, messageid, id ' 'FROM pings ' 'WHERE lower(recipient) == ? ' ';', (nick.lower(), )).fetchall() for pong in pongs: if pong[2] + _posts_since_ping > rawMessage['id']: pingProperties['print'] = False # ~ pongSplit = split_with_quotation_marks(pong[1]) # ~ if len(pongSplit) >= 3 \ # ~ and pongSplit[0].startswith('-') \ # ~ and pongSplit[0][1:] == 'pong': # ~ pongTime = datetime.datetime(*parsedatetime.Calendar().parse(pongSplit[1])[0][:6]) # ~ if datetime.datetime.now() < pongTime: # ~ pingProperties['print'] = False # ~ else: # ~ pingProperties['delete'] = False if pingProperties['print'] == True: if message == None: message = rawMessage[ 'name'] + ', dir wollte jemand etwas sagen:' message += '\n' + pong[0] + ' sagte: ' + pong[1] else: pingProperties['ping'] = True if pingProperties['delete']: cursor.execute('DELETE ' 'FROM pings ' 'WHERE id == ? ' ';', (pong[3], )) db_connection.commit() if len(args) >= 2 and args[0] == '!ping' and ''.join(args[2:]).strip( ''.join(_space_chars)) != '': cursor = db_connection.cursor() pingCount = cursor.execute( 'SELECT count(*) ' 'FROM pings ' 'WHERE recipient == ? ' 'AND sender == ? ' ';', (args[1], rawMessage['name'])).fetchone() if pingCount[0] == 0: cursor.execute( 'INSERT OR REPLACE ' 'INTO pings ' '(recipient, message, sender, messageid) ' 'VALUES (?, ?, ?, ?)' ';', ( args[1], stripFromBegin(rawMessage['message'], args[0:2]), rawMessage['name'], rawMessage['id'], )) else: cursor.execute( 'UPDATE pings ' 'SET message = ?, messageid = ? ' 'WHERE recipient = ? ' 'AND sender = ?' ';', ( ''.join(x + ' ' for x in args[2:]).strip(), rawMessage['id'], args[1], rawMessage['name'], )) db_connection.commit() if message is not None: return helper.botMessage(message, _botname)
def processMessage(args, rawMessage, db_connection): if len(args) == 1 and args[0].lower() == "!" + _bottrigger: news = get_all() return helper.botMessage("\n".join(map(format_news, news)), _botname)
def processMessage(args, rawMessage, db_connection): if len(args) < 2: return None if args[0].lower() != '!' + _bottrigger.lower(): return if args[1] == 'ping': return helper.botMessage('Hallu', _botname) elif args[1].lower() == 'ud': return elif args[1].lower() == 'decide': return elif args[1].lower().startswith('sing'): return parser = argparse.ArgumentParser(prog='!rita sing') parser.add_argument('song', nargs='?') parser.add_argument('-l', '--learn', action='store_true', dest='learn') parser.add_argument('-a', '--add', action='store_true', dest='learn') parser.add_argument('-r', '--remove', action='store_true', dest='remove') parser.add_argument('-h', '--help', action='store_true') parser.add_argument('-c', '--count', action='store_true') parser.add_argument('-v', '--version', action='store_true') # needed try: parsedArgs = vars(parser.parse_known_args(args[2:])[0]) except argparse.ArgumentError: return helper.botMessage(parser.print_usage(), _botname) if (( parsedArgs['learn'] or parsedArgs['remove'] ) and parsedArgs['song'] == None) or \ parsedArgs['help']: return helper.botMessage(parser.format_usage().rstrip('\n'), _botname) elif parsedArgs['version']: return helper.botMessage('secret unlocked \o/ the first one calling w/ID gets some chocolate', _botname) if parsedArgs['learn']: return learntosing(parsedArgs['song'], db_connection) elif parsedArgs['remove']: if True or rawMessage['username'] in botMasters: return removeasong(parsedArgs['song'], db_connection) else: return helper.botMessage('DU bist nicht mein botmaster. ich bin gescheitert', _botname) elif parsedArgs['count']: return helper.botMessage('Ich kann schon %s Lieder singen :) *stolz*'%songCount(db_connection.cursor()), _botname) return helper.botMessage(singasong(db_connection.cursor()), _botname) elif args[1].lower() in [_slap_trigger, _featurerequest_trigger]: return if len(args) == 2: return helper.botMessage('was meinst du?', _botname) target = stripFromBegin(rawMessage['message'], args[0:2]) if args[1] == _slap_trigger: return helper.botMessage('%s schlägt %s'%(_botname.replace('Dr. Ritastein', 'Rita'), target), _botname) elif args[1] == _featurerequest_trigger: return helper.botMessage('Ich will %s'%target, _botname) else: return helper.botMessage(_help, _botname)