diff --git a/api/db/telethon_db.py b/api/db/telethon_db.py index 30d61d3..f27a9f1 100644 --- a/api/db/telethon_db.py +++ b/api/db/telethon_db.py @@ -11,7 +11,6 @@ import datetime import sqlite3 import uuid import os -from telethon.sync import TelegramClient from .db import Database class TelethonDatabase(Database): @@ -29,17 +28,6 @@ class TelethonDatabase(Database): """ super(TelethonDatabase, self).__init__(database) - # Load in the API tokens required for a bot - api_id = os.environ.get('telethon_api_id', False) - api_hash = os.environ.get('telethon_api_hash', False) - api_token = os.environ.get('telethon_token', False) - - # Create an instance of the Telethon bot - if api_id and api_hash and api_token: - self.bot = TelegramClient('bot', api_id, api_hash).start(bot_token=api_token) - else: - self.bot = False - # Automatically create the table if it doesn't # already exist in the selected database self._create_table() diff --git a/server.py b/server.py index e902330..4464f1a 100644 --- a/server.py +++ b/server.py @@ -6,11 +6,44 @@ This file contains the web server for a simple bookmarking application """ +import os +import _thread from bottle import Bottle, run, response, route, template from api import API +from telethon.sync import TelegramClient, events _api = API() +# Load in the API tokens required for a telegram bot +api_id = os.environ.get('telethon_api_id', False) +api_hash = os.environ.get('telethon_api_hash', False) +api_token = os.environ.get('telethon_token', False) + +# Create an instance of the Telethon bot +if api_id and api_hash and api_token: + bot = TelegramClient('bot', api_id, api_hash).start(bot_token=api_token) +else: + bot = False + +bot_state = False + +@bot.on(events.NewMessage) +async def handle_message_events(event): + if 'start' in event.raw_text: + await event.reply('started') + +def start_bot_thread(): + """ + We run the telegram bot in a seperate thread + to be able to also serve the HTTP content. + + The bot thread will be idle most of the time + due to the async nature of it, and the fact + that it won't receive much traffic + """ + bot.start() + bot.run_until_disconnected() + @route('/') def index(): return "This is the index" @@ -42,4 +75,6 @@ def update_bookmark_uri(bookmark_id, uri): return _api.update_bookmark_uri(bookmark_id, uri) if __name__ == '__main__': + # Start the Telegram bot and the bottle server + _thread.start_new_thread(start_bot_thread, ()) run(host='localhost', port=8080)