From 01019f11866c14c882a6c7695c390ecbc2e76d36 Mon Sep 17 00:00:00 2001 From: Stan James Date: Sun, 28 Jan 2018 22:29:50 -0700 Subject: [PATCH] Cleaned up README and moved config info out of version control Clarified naming of some things. --- .gitignore | 24 ++++++++++++++++++++++++ README.md | 39 ++++++++++++++++++++++++++------------- bot.py | 30 +++++++++++++++--------------- config.cnf.sample | 2 ++ model.py | 25 +++++++++++++++---------- requirements.txt | 3 ++- 6 files changed, 84 insertions(+), 39 deletions(-) create mode 100644 .gitignore create mode 100644 config.cnf.sample diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..74d14ea --- /dev/null +++ b/.gitignore @@ -0,0 +1,24 @@ +# Never commit config data +config.cnf + +# Byte-compiled / optimized / DLL files +*.py[cod] + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +origin-telegram-logger-bot diff --git a/README.md b/README.md index d9c0c2d..725b1e3 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,36 @@ # Telegram Group Chat Logger -This is a bot that logs public Group Chats to an SQL Database. +This is a bot that logs public Group Chats to a Postgres Database. ## Installation - - Required: Python 3.X , PostgreSQL, Telegram Bot + - Required: Python 3.x, pip, PostgreSQL - Clone this repo - - `pip install requirements.txt` - -## Bot/Group Setup + - `pip install --upgrade -r requirements.txt` - - Create a group +## Telegram Bot Setup + + - Create a bot by talking to BotFather: https://core.telegram.org/bots#creating-a-new-bot + - Store your Telegram Bot Token in environment variable `BOT_TOKEN`. It will look similar to this: + ``` + export TELEGRAM_BOT_TOKEN="4813829027:ADJFKAf0plousH2EZ2jBfxxRWFld3oK34ya" + ``` + - Create a Telegram group. - Add your bot to the group like so: https://stackoverflow.com/questions/37338101/how-to-add-a-bot-to-a-telegram-group - - your bot only sees commands. Use `/setprivacy` with `@BotFather` in order to allow it to see all messages in a group. - + - Your bot only sees commands. Use `/setprivacy` with `@BotFather` in order to allow it to see all messages in a group. + ## Running the bot - - Create a Database, eg. `origindb` - - Store your Telegram Bot Token in an environment variable, eg. `echo $ORIGINTOKEN` - - Add your DB credentials to `model.py` eg. `engine = create_engine('postgresql://postgres:@localhost:5432/')` - - Run: `python model.py` to setup the DB tables, etc. - - Run: `python bot.py` to start logger \ No newline at end of file + - Create a Postgres database. + ``` + $psql +CREATE DATABASE telegram_bot_db; +``` + - Copy `config.cnf.sample` to `config.cnf` and edit the databse connection URL. File should look like this: + ``` +[postgres] +postgres_url = postgresql://:@localhost:5432/ +``` + - Run: `python model.py` to setup the DB tables. + - Run: `python bot.py` to start logger + - When a messages is successfully logged, `message logged` will be displayed. diff --git a/bot.py b/bot.py index 8f17b1d..463aa02 100644 --- a/bot.py +++ b/bot.py @@ -2,7 +2,7 @@ """Group Chat Logger -This bot is a modified version of the echo2 bot found here: +This bot is a modified version of the echo2 bot found here: https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py This bot logs all messages sent in a Telegram Group to a database. @@ -25,22 +25,22 @@ logger = logging.getLogger(__name__) def logger(bot, update): """Primary Logger. Handles incoming bot messages and saves them to DB""" - + user = update.message.from_user if id_exists(user.id) == True: log_message(user.id, update.message.text) print("message logged") - + else: add_user_success = add_user(user.id, user.first_name, user.last_name, user.username) - + if add_user_success == True: log_message(user.id, update.message.text) print("user added & message logged") else: print("Something went wrong adding the user!") - + # DB queries def id_exists(id_value): @@ -49,9 +49,9 @@ def id_exists(id_value): for id1 in s.query(User.id).filter_by(id=id_value): if id1: bool_set = True - + s.close() - + return bool_set def log_message(user_id, user_message): @@ -62,10 +62,10 @@ def log_message(user_id, user_message): s.add(msg1) s.commit() s.close() - + except Exception as e: print(e) - + def add_user(user_id, first_name, last_name, username): try: s = session() @@ -74,15 +74,15 @@ def add_user(user_id, first_name, last_name, username): s.add(user) s.commit() s.close() - + if id_exists(user_id) == True: bool_set = True - + return bool_set - + except Exception as e: print(e) - + def error(bot, update, error): """Log Errors caused by Updates.""" @@ -92,7 +92,7 @@ def error(bot, update, error): def main(): """Start the bot.""" # Create the EventHandler and pass it your bot's token. - updater = Updater(os.environ["ORIGINTOKEN"]) + updater = Updater(os.environ["TELEGRAM_BOT_TOKEN"]) # Get the dispatcher to register handlers dp = updater.dispatcher @@ -101,7 +101,7 @@ def main(): # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, logger)) - + # dp.add_handler(MessageHandler(Filters.status_update, status)) # log all errors diff --git a/config.cnf.sample b/config.cnf.sample new file mode 100644 index 0000000..44b503c --- /dev/null +++ b/config.cnf.sample @@ -0,0 +1,2 @@ +[postgres] +postgres_url = postgresql://:@localhost:5432/ diff --git a/model.py b/model.py index 6508606..e819443 100644 --- a/model.py +++ b/model.py @@ -1,22 +1,26 @@ from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func from sqlalchemy.orm import relationship, backref from sqlalchemy.ext.declarative import declarative_base +import ConfigParser +config = ConfigParser.ConfigParser() +config.read("config.cnf") +postgres_url = config.get('postgres', 'postgres_url') ''' This model has been referenced from: https://www.pythoncentral.io/sqlalchemy-orm-examples/ -''' - +''' + Base = declarative_base() - - + + class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) first_name = Column(String) last_name = Column(String) username = Column(String) - - + + class Message(Base): __tablename__ = 'messages' id = Column(Integer, primary_key=True) @@ -26,12 +30,13 @@ class Message(Base): # of an Employee to be the current time when an # Employee record was created time = Column(DateTime, default=func.now()) - - + + from sqlalchemy import create_engine -engine = create_engine('postgresql://postgres:@localhost:5432/origindb') - +engine = create_engine(postgres_url) + from sqlalchemy.orm import sessionmaker session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) +print "Created database model" diff --git a/requirements.txt b/requirements.txt index ca2a98c..61068ff 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ psycopg2==2.7.3.2 python-telegram-bot==9.0.0 -SQLAlchemy==1.2.2 \ No newline at end of file +SQLAlchemy==1.2.2 +configparser==3.5.0