Пример #1
0
async def HandleSelfMessage(client, chan, msg):
	#Cache user details if they are new
	if not client.usr_name.lower() in glob.cached_users.keys():
		userObject.User(client.usr_name)
	
	try:
		hooks = await chan.webhooks()
		if len(hooks) == 0:
			hook = await chan.create_webhook(name="{}/{}".format(chan.category.name, chan.name))
		else:
			hook = hooks[0]
		
		msg = dMessage.DiscordMessage(client.usr_name.replace(" ","_"), msg)
		query = json.dumps(msg.__dict__)
		req = requests.post("{}/slack".format(hook.url), data=query)
	except Exception as e:
		print("ERROR: {}".format(e))
Пример #2
0
    def LoadFromDatabase(self):
        #Settings
        self.cursor.execute("SELECT * FROM settings")
        rows = self.cursor.fetchall()
        for row in rows:
            glob.settings[row["name"]] = row["value_string"] if row[
                "value_int"] == None else row["value_int"]

        #Ignore_categories setup
        glob.ignore_categories = glob.settings[
            "discord_ignore_categories"].split(",")

        #Accounts
        self.cursor.execute("SELECT * FROM accounts")
        rows = self.cursor.fetchall()
        for row in rows:
            if row["is_bot"]:
                glob.irc_clients[row["irc_username"]] = ircclient.IRCClientBot(
                    row["irc_username"], row["irc_token"])
            else:
                glob.irc_clients[
                    row["discord_snowflake"]] = ircclient.IRCClientUser(
                        row["discord_snowflake"], row["irc_username"],
                        row["irc_token"], row["allow_dm"],
                        row["always_online"], json.loads(row["highlights"]))
                glob.irc_snowflake_link[
                    row["irc_username"]] = row["discord_snowflake"]

        #Setup highlight table
        for client in glob.irc_clients.values():
            for highlight in client.highlights:
                glob.highlight_list[highlight] = "<@{}>".format(
                    client.discord_snowflake)

        #Cached Users
        self.cursor.execute("SELECT * FROM cached_users")
        rows = self.cursor.fetchall()
        for row in rows:
            glob.cached_users[row["username_safe"].lower()] = user.User(
                row["username_safe"], row["userid"], row["username"],
                row["avatar"], row["silenced"])
Пример #3
0
def process_message(message, chat):
    usr = user.User(message.sender)

    if usr.state() == 'timezone':
        if message.location is None:
            message.reply(usr.getstr('ask_timezone_no_location'))
            return True

        lat = message.location.latitude
        lon = message.location.longitude
        result = gmaps.timezone([lat, lon]).get('timeZoneId', False)
        if not result:
            message.reply(usr.getstr('ask_timezone_no_results'))
            return True

        usr.timezone(result)
        start(chat, message, args=[])

    update = message_update.MessageUpdate(usr, bot, chat, message)
    trends.process_message(update)
    calendar.process_message(update)
    drive.process_message(update)
Пример #4
0
async def HandleMessage(ircclient, channel, user, message):
	#Cache user details if they are new
	if not user.lower() in glob.cached_users.keys():
		userObject.User(user)

	no_lower_user = user
	channel = channel.lower()		#Discord channels only accept lowercase
	user = user.lower()				#^
	message = message.replace("@", "(@)")		#Quickfix to disable highlights
	
	private = True
	if channel.startswith("#"):
		private = False
		channel = channel[1:] #Remove first char so we got the raw channel name

	if not private:
		#Adds highlights
		for k, v, in glob.highlight_list.items():
			message = re.sub(k, v, message, flags=re.IGNORECASE)
	
	try:
		c = glob.discordclient.get_guild(glob.settings["discord_guild"])
		cats = c.categories
		#chas = c.text_channels
		if private:
			if not any(x.name in ircclient.usr_name for x in cats):
				cat = await c.create_category(ircclient.usr_name, overwrites={ c.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False),  glob.discordclient.get_user(ircclient.discord_snowflake): discord.PermissionOverwrite(add_reactions=True, read_messages=True, send_messages=True, embed_links=True, manage_messages=True, read_message_history=True, ) })
			else:
				cat = next(x for x in cats if x.name == ircclient.usr_name)

			if not any(x.name in user for x in cat.channels):
				chan = await c.create_text_channel(user, category=cat)
			else:
				chan = next(x for x in cat.channels if x.name == user)

			hooks = await chan.webhooks()
			if len(hooks) == 0:
				hook = await chan.create_webhook(name="{}/{}".format(cat.name, chan.name))
			else:
				hook = hooks[0]
		else:
			if not any(x.name == glob.settings["discord_main_category"] for x in cats):
				cat = await c.create_category(glob.settings["discord_main_category"])
			else:
				cat = next(x for x in cats if x.name == glob.settings["discord_main_category"])
			
			if not any(x.name in channel for x in cat.channels):
				chan = await c.create_text_channel(channel, category=cat)
			else:
				chan = next(x for x in cat.channels if x.name == channel)
			
			hooks = await chan.webhooks()
			if len(hooks) == 0:
				hook = await chan.create_webhook(name="#{}".format(chan.name))
			else:
				hook = hooks[0]

		message = dMessage.DiscordMessage(no_lower_user.replace(" ", "_"), message) #Convert to discordmessage object for json serialization
		query = json.dumps(message.__dict__)
		req = requests.post("{}/slack".format(hook.url), data=query)
	except Exception as e:
		print("ERROR: {}".format(e))
Пример #5
0
def ClientConnectionThread(conn, addr):
    try:
        logger.info("Client connected from " + str(addr))
        
        byteData = conn.recv(1024) # Receive serverInfoRequest
        data = encoding.DecodePlain(byteData) 
        
        sendMessage(conn, "", "serverInfo", server.RSAPublicToSend, enc=False)

        byteData = conn.recv(1024) # Receive clientSecret
        data = encoding.DecodePlain(byteData)

        userSecret = server.RSAPrivate.decrypt(base64.b64decode(data["data"]))

        sendMessage(conn, userSecret, "gotSecret", "")

        byteData = conn.recv(1024) # Receive connectionRequest
        data = encoding.DecodeEncrypted(byteData, userSecret)

        connectionRequest = json.loads(data["data"])

        currentUser = user.User(data["userid"], connectionRequest[0], userSecret, addr, conn)

        currentUser.connectionValid = True
        isServerFull = server.IsServerFull()
        if isServerFull:
            connInvalidReason = "Server is full"
            currentUser.connectionValid = False
            logger.warning("Client " + str(addr) + " tried to join but the server was full")
        validPassword = server.Authenticate(connectionRequest[1]);
        if validPassword == False:
            connInvalidReason = "Incorrect Password"
            currentUser.connectionValid = False
            logger.warning("Client " + str(addr) + " used incorrect password")
        isNotBanned = server.IsNotBanned(currentUser)
        if isNotBanned == False:
            connInvalidReason = "You are banned from this server"
            currentUser.connectionValid = False
            logger.warning("Client " + str(addr) + " tried to join but was banned")
        validID = server.ValidID(currentUser)
        if validID == False:
            connInvalidReason = "Invalid eID"
            currentUser.connectionValid = False
            logger.warning("Client " + str(addr) + " tried to join but was already connected from the same device")
        if connectionRequest[2] not in server.compatibleClientVers:
            connInvalidReason = "Incompatible Client version"
            currentUser.connectionValid = False
            logger.warning("Client " + str(addr) + " tried to join but was has an incompatible client version")
        validUsername = server.ValidUsername(currentUser)
        currentUser.username = validUsername
        
    except ConnectionResetError:
        logger.error("Client " + str(addr) + " disconnected during handshake")
    
    if currentUser.connectionValid == True:
        try:
            sendMessage(conn, userSecret, "CRAccepted", "")
            server.AddUser(currentUser)
            sendMessage(conn, userSecret, "serverData", server.packagedData)
            logger.info("Client " + str(addr) + " completed handshake")
            while currentUser.connectionValid:
                    byteData = conn.recv(1024)
                    data = encoding.DecodeEncrypted(byteData, currentUser.secret)
                    logger.info("Received messagetype " + data["messagetype"] + " from client " + str(addr))
                    if data["messagetype"] == "disconnect":
                        disconnect.handle(conn, addr, currentUser, server, data) 
                        break
                    elif data["messagetype"] == "userMessage":
                        userMessage.handle(conn, addr, currentUser, server, data) 
                    elif data["messagetype"] == "changeChannel":
                        changeChannel.handle(conn, addr, currentUser, server, data)
                    elif data["messagetype"] == "historyRequest":
                        historyRequest.handle(conn, addr, currentUser, server, data)
                    elif data["messagetype"] == "leaveChannel":
                        leaveChannel.handle(conn, addr, currentUser, server, data)
        except json.decoder.JSONDecodeError:
            logger.error("Received illegal disconnect from client " + str(addr))
            disconnect.handle(conn, addr, currentUser, server, data)
            currentUser.connectionValid = False
        except ConnectionResetError:
            logger.error("Received illegal disconnect from client " + str(addr))
            disconnect.handle(conn, addr, currentUser, server, data)
            currentUser.connectionValid = False
        except ConnectionAbortedError as e:
            if currentUser.connectionValid == False:
                pass
            else:
                logger.error(e)
    else:
        logger.warning("Client " + str(addr) + " failed handshake");
        sendMessage(conn, userSecret, "CRDenied", connInvalidReason)
        conn.close()

    conn.close()
Пример #6
0
def process_callback(bot, chains, update):
    cb = callback.Callback(update)
    usr = user.User(cb.sender)

    if 'l@' in cb.query:
        usr.language(new_language=cb.query.replace('l@', ''))
        if usr.logged_in:
            cb.query = 'home'

    if not usr.logged_in and usr.exists:
        bot.api.call(
            'editMessageText', {
                'chat_id':
                cb.chat.id,
                'message_id':
                cb.message.message_id,
                'text':
                usr.getstr('sign_in'),
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard': [[{
                        "text": usr.getstr('sign_in_button'),
                        "url": oauth.get_url()
                    }]]
                })
            })
        return

    if cb.query == 'sign_in':
        bot.api.call("answerCallbackQuery", {
            'callback_query_id': cb.id,
            'url': 'telegram.me/your_bot?start=XXXX'
        })

    if not usr.exists:
        text = ("<b>Welcome!</b>" "\nFirst, <b>select your language</b>:")
        bot.api.call(
            'editMessageText', {
                'chat_id':
                cb.chat.id,
                'message_id':
                cb.message.message_id,
                'text':
                text,
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard': [[{
                        "text": "🇮🇹 Italian",
                        "callback_data": "l@it"
                    }, {
                        "text": "🇬🇧 English",
                        "callback_data": "l@en"
                    }, {
                        "text": "🇪🇸 Spanish",
                        "callback_data": "l@es"
                    }]]
                })
            })

    if cb.query == 'home':
        bot.api.call(
            'editMessageText', {
                'chat_id':
                cb.chat.id,
                'message_id':
                cb.message.message_id,
                'text':
                usr.getstr('start'),
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    "inline_keyboard": [
                        [{
                            "text": usr.getstr('news_button'),
                            "callback_data": "news"
                        }, {
                            "text": usr.getstr('trends_button'),
                            "callback_data": "trends"
                        }, {
                            "text": usr.getstr('calendar_button'),
                            "callback_data": "calendar"
                        }],
                        [{
                            "text": usr.getstr('drive_button'),
                            "callback_data": "drive"
                        }],
                        [{
                            "text": usr.getstr('settings_button'),
                            "callback_data": "settings"
                        }],
                    ]
                })
            })

    elif cb.query == 'settings':
        bot.api.call(
            'editMessageText', {
                'chat_id':
                cb.chat.id,
                'message_id':
                cb.message.message_id,
                'text':
                usr.getstr('settings'),
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard': [[{
                        "text": usr.getstr('setlang_button'),
                        "callback_data": "setlang"
                    }],
                                        [{
                                            "text": usr.getstr('back_button'),
                                            "callback_data": "home"
                                        }]]
                })
            })

    elif cb.query == 'setlang':
        bot.api.call(
            'editMessageText', {
                'chat_id':
                cb.chat.id,
                'message_id':
                cb.message.message_id,
                'text':
                usr.getstr('setlang'),
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard': [[{
                        "text": "🇮🇹 Italian",
                        "callback_data": "l@it"
                    }, {
                        "text": "🇬🇧 English",
                        "callback_data": "l@en"
                    }, {
                        "text": "🇪🇸 Spanish",
                        "callback_data": "l@es"
                    }]]
                })
            })

    elif cb.query == 'trends':
        usr.state(new_state='trends1')
        bot.api.call(
            'editMessageText', {
                'chat_id':
                cb.chat.id,
                'message_id':
                cb.message.message_id,
                'text':
                usr.getstr('trends'),
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard': [[{
                        "text": usr.getstr('back_button'),
                        "callback_data": "home"
                    }]]
                })
            })

    elif cb.query == 'calendar':
        text, inline_keyboard = calendar.getevents(usr, [None, 3])
        bot.api.call(
            'editMessageText', {
                'chat_id': cb.chat.id,
                'message_id': cb.message.message_id,
                'text': text,
                'parse_mode': 'HTML',
                'disable_web_page_preview': True,
                'reply_markup': inline_keyboard
            })

    elif cb.query == 'drive':
        text, inline_keyboard = drive.getfiles(user=usr,
                                               pagetoken=None,
                                               parent='root')
        bot.api.call(
            'editMessageText', {
                'chat_id': cb.chat.id,
                'message_id': cb.message.message_id,
                'text': text,
                'parse_mode': 'HTML',
                'disable_web_page_preview': True,
                'reply_markup': inline_keyboard
            })

    news.process_callback(bot, cb, usr)
    calendar.process_callback(bot, cb, usr)
    drive.process_callback(bot, cb, usr)
Пример #7
0
def start(chat, message, args):
    usr = user.User(message.sender)
    usr.state('home')

    if 'oauth-' in ''.join(args):
        short_code = ''.join(args).replace('oauth-', '')
        c.execute('SELECT code FROM cache_oauth_codes WHERE short_code=?',
                  (short_code, ))
        code = c.fetchone()[0]
        oauth.save(usr, code)

        c.execute('DELETE FROM cache_oauth_codes WHERE code=?', (code, ))
        conn.commit()

    if 'cd-edit-' in ''.join(args):
        short_event_id = ''.join(args).replace('cd-edit-', '')
        c.execute('SELECT id FROM cache_calendar_event_ids WHERE short_id=?',
                  (short_event_id, ))
        event_id = c.fetchone()[0]

        text = calendar.formatevent(usr, event_id)
        bot.api.call(
            'sendMessage', {
                'chat_id':
                chat.id,
                'text':
                text,
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard':
                    [[{
                        "text": usr.getstr('edit_event_button'),
                        "callback_data": "cd@edit@" + short_event_id
                    }, {
                        "text": usr.getstr('delete_event_button'),
                        "callback_data": "cd@delete@" + short_event_id
                    }],
                     [{
                         "text": usr.getstr('back_button'),
                         "callback_data": "home"
                     }]]
                })
            })
        return True

    if 'drv-file-' in ''.join(args):
        if '-download' in ''.join(args):
            args = ''.join(args)
            file = args.lstrip('drv-file').rstrip('-download')

            msg = chat.send(
                usr.getstr('drive_downloading_progress').format(p=0))
            try:
                filename = drive.download(usr, drive.getfile(usr, file), msg)
            except:
                msg.edit('Unable to download the file.')
                return

            msg.edit(usr.getstr('drive_downloading_uploading'))

            if os.path.getsize(filename) > 50000000:
                msg.edit('File is too big for be sent.')
                return

            if filename.endswith('.png') or filename.endswith('.jpg'):
                message.reply_with_photo(filename)
            elif filename.endswith('.mp3'):
                message.reply_with_audio(filename)
            elif filename.endswith('.ogg'):
                message.reply_with_voice(filename)
            else:
                message.reply_with_file(filename)

            msg.edit(usr.getstr('drive_downloading_done'))
            os.remove(filename)
            return

        if '-delete' in ''.join(args):
            args = ''.join(args)
            file = args.lstrip('drv-file').rstrip('-delete')

            bot.api.call(
                'sendMessage', {
                    'chat_id':
                    chat.id,
                    'text':
                    usr.getstr('drive_delete_confirm'),
                    'parse_mode':
                    'HTML',
                    'reply_markup':
                    json.dumps({
                        "inline_keyboard":
                        [[{
                            "text": usr.getstr('drive_delete_button'),
                            "callback_data": "drv@file@" + file + "@delete"
                        }, {
                            "text": usr.getstr('back_button'),
                            "callback_data": "drive"
                        }]]
                    })
                })
            return

    if not usr.exists:
        text = ("<b>Welcome!</b>" "\nFirst, <b>select your language</b>:")
        bot.api.call(
            'sendMessage', {
                'chat_id':
                chat.id,
                'text':
                text,
                'parse_mode':
                'HTML',
                'reply_markup':
                json.dumps({
                    'inline_keyboard': [[{
                        "text": "🇮🇹 Italian",
                        "callback_data": "l@it"
                    }, {
                        "text": "🇬🇧 English",
                        "callback_data": "l@en"
                    }, {
                        "text": "🇪🇸 Spanish",
                        "callback_data": "l@es"
                    }]]
                })
            })
        return

    if not usr.timezone():
        chat.send(usr.getstr('ask_timezone'))
        usr.state('timezone')
        return

    bot.api.call(
        'sendMessage', {
            'chat_id':
            chat.id,
            'text':
            usr.getstr('start'),
            'parse_mode':
            'HTML',
            'reply_markup':
            json.dumps({
                "inline_keyboard": [[{
                    "text": usr.getstr('news_button'),
                    "callback_data": "news"
                }, {
                    "text": usr.getstr('trends_button'),
                    "callback_data": "trends"
                }, {
                    "text": usr.getstr('calendar_button'),
                    "callback_data": "calendar"
                }],
                                    [{
                                        "text": usr.getstr('drive_button'),
                                        "callback_data": "drive"
                                    }],
                                    [{
                                        "text": usr.getstr('settings_button'),
                                        "callback_data": "settings"
                                    }]]
            })
        })