hellsbot.py 8.36 KB
import requests
import discord
import random
import datetime

from ago import human
import simplejson as json

member_status = 'members.json'
fortune_file = 'fortunes.json'
games_file = 'games.json'
credentials = 'creds.json'

client = discord.Client()

json_data=open(credentials).read()
creds = json.loads(json_data)
client.login(creds['username'], creds['password'])

def byteify(input):
    if isinstance(input, dict):
        return {byteify(key):byteify(value) for key,value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input


@client.event
def on_status(member):
    print("Status Changed %s" % (member,))
    try:
        json_data=open(member_status).read()
        data = json.loads(json_data)
    except ValueError:
        data = {}
    if not data:
        data = {}
    try:
        username = member.name.lower()
        if username in data:
            is_afk = data[username]['is_afk']
            afk_at = data[username]['afk_at']
            status = data[username]['status']
            prev_status = data[username]['prev_status']
            status_change_at = data[username]['status_change_at']
            game_id = data[username]['game_id']
            games_played = data[username]['games_played']
        else:
            is_afk = False
            afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
            status = 'online'
            prev_status = 'offline'
            status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
            game_id = None
            games_played = []
        if member.status == 'idle':
            afk_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
            is_afk = True
        else:
            is_afk = False
        if status != member.status:
            prev_status = status
            status = member.status
            status_change_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        if game_id != member.game_id:
            game_id = member.game_id
            if game_id not in games_played:
                games_played.append(game_id)
        data[username] = {
            'is_afk': is_afk,
            'afk_at': afk_at,
            'status': status,
            'prev_status': prev_status,
            'status_change_at': status_change_at,
            'game_id': game_id,
            'games_played': games_played
        }
        print('Status Change: %s' % (data,))
        jdata = json.dumps(data, ensure_ascii=False)
    except Exception as e:
        print('Error saving status change: %s' % (e),)
        return            

    open(member_status, 'wb+').write(jdata.encode('utf8'))
    

def get_game_names(game_id_list):
    json_data=open(games_file).read()
    data = json.loads(json_data)
    result = []
    for game_id in game_id_list:
        for game in data:
            if game['id'] == game_id:
                result.append(game['name'])
    return result

@client.event
def on_message(message):
    print message.content
    print message.author
    print client.user
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.lower().startswith(client.user.name.lower()):
        print('Someone is talking to %s' % (client.user.name.lower(),))
        if ' or ' in message.content:
            questions = message.content[len(client.user.name)+1:].replace('?', '').split(' or ')
            client.send_message(message.channel, '{} I choose: {}'.format(message.author.mention(), random.choice(questions).encode('utf-8',errors='ignore')))


    if message.content.startswith('!help') or message.content.startswith('!commands'):
        client.send_message(message.channel, '{} Available Commands:\nYou can ask compound or questions and I will choose. Example: HellsBot Rui is a Faggot or Rui is a faggot?\n!games <username> - Returns a list of games played\n!lastseen <username> - Returns info on when the user was last seen and their status\n!addfortune <fortune>\n!fortune\n!secret\n!bemyirlwaifu'.format(message.author.mention()))
        return

    if message.content.startswith('!lastseen'):
        data = None
        try:
            json_data=open(member_status).read()
            data = json.loads(json_data)
        except ValueError:
            pass
        if not data:
            client.send_message(message.channel, 'I am a bit confused right now.. maybe I need more data. {}!'.format(message.author.mention()))            
        else:
            username = message.content[10:].replace('@', '').lower()
            if username in data:
                out_string = ''
                if data[username]['is_afk'] == True:
                    out_string = 'Went AFK at: {}\n'.format(data[username]['afk_at'])
                elif data[username]['status'] == 'offline':
                    out_string = 'Currently Offline\n'                    
                else:
                    out_string = 'Currently Online\n'
                out_string += 'Last Status: {} at {} which was {}\nPrevious Status: {}\n'.format(data[username]['status'], 
                    data[username]['status_change_at'], 
                    human(datetime.datetime.strptime(data[username]['status_change_at'], '%Y/%m/%d %H:%M:%S')),
                    data[username]['prev_status'])

                client.send_message(message.channel, 'Last Information on {}:\n{}'.format(username, out_string))
            else:
                client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))

    if message.content.startswith('!games'):
        data = None
        try:
            json_data=open(member_status).read()
            data = json.loads(json_data)
        except ValueError:
            pass
        if not data:
            client.send_message(message.channel, 'I am a bit confused right now.. maybe I need more data. {}!'.format(message.author.mention()))            
        else:
            username = message.content[7:].replace('@', '').lower()
            if username in data:
                games = ', '.join(get_game_names(data[username]['games_played']))
                client.send_message(message.channel, 'I have seen {} playing: {}'.format(username, games))
            else:
                client.send_message(message.channel, 'I don\'t have any data on {} yet {}'.format(username, message.author.mention()))

    if message.content.startswith('!addfortune'):
        try:
            json_data=open(fortune_file).read()
            data = json.loads(json_data)
        except ValueError:
            data = []
        if not data:
            data = []
        try:
            data.append(byteify(message.content[12:]))
            jdata = json.dumps(data, ensure_ascii=False)
        except:
            client.send_message(message.channel, 'Your shitty fortune has been rejected {}.'.format(message.author.mention()))
            return            

        open(fortune_file, 'wb+').write(jdata.encode('utf8'))
        client.send_message(message.channel, 'Your shitty fortune has been added {}.'.format(message.author.mention()))            
    if message.content.startswith('!fortune'):
        data = None
        try:
            json_data=open(fortune_file).read()
            data = json.loads(json_data)
        except ValueError:
            pass
        if not data:
            client.send_message(message.channel, 'Try adding a fortune with "!addfortune <fortune>" {}!'.format(message.author.mention()))            
        else:
            client.send_message(message.channel, '{} Your fortune is... {}'.format(message.author.mention(), random.choice(data).encode('utf-8',errors='ignore')))

    if message.content.startswith('!secret'):
        client.send_message(message.channel, 'git gud {}!'.format(message.author.mention()))

    if message.content.startswith('!bemyirlwaifu'):
        client.send_message(message.channel, 'http://orig13.deviantart.net/b25e/f/2014/175/3/d/no_waifu_no_laifu_by_imtheonenexttome-d7nsx3b.gif {}!'.format(message.author.mention()))


    if message.content.startswith('!hello'):
        client.send_message(message.channel, 'Hello {}!'.format(message.author.mention()))

@client.event
def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run()