Cleaned up README and moved config info out of version control

Clarified naming of some things.
This commit is contained in:
Stan James 2018-01-28 22:29:50 -07:00
parent 68cf51aa3e
commit 01019f1186
6 changed files with 84 additions and 39 deletions

24
.gitignore vendored Normal file
View File

@ -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

View File

@ -1,23 +1,36 @@
# Telegram Group Chat Logger # 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 ## Installation
- Required: Python 3.X , PostgreSQL, Telegram Bot - Required: Python 3.x, pip, PostgreSQL
- Clone this repo - Clone this repo
- `pip install requirements.txt` - `pip install --upgrade -r requirements.txt`
## Bot/Group Setup
- 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 - 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 ## Running the bot
- Create a Database, eg. `origindb` - Create a Postgres database.
- 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:<password>@localhost:5432/<databasename>')` $psql
- Run: `python model.py` to setup the DB tables, etc. CREATE DATABASE telegram_bot_db;
- Run: `python bot.py` to start logger ```
- Copy `config.cnf.sample` to `config.cnf` and edit the databse connection URL. File should look like this:
```
[postgres]
postgres_url = postgresql://<user>:<password>@localhost:5432/<databasename>
```
- 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.

30
bot.py
View File

@ -2,7 +2,7 @@
"""Group Chat Logger """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 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. 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): def logger(bot, update):
"""Primary Logger. Handles incoming bot messages and saves them to DB""" """Primary Logger. Handles incoming bot messages and saves them to DB"""
user = update.message.from_user user = update.message.from_user
if id_exists(user.id) == True: if id_exists(user.id) == True:
log_message(user.id, update.message.text) log_message(user.id, update.message.text)
print("message logged") print("message logged")
else: else:
add_user_success = add_user(user.id, user.first_name, user.last_name, user.username) add_user_success = add_user(user.id, user.first_name, user.last_name, user.username)
if add_user_success == True: if add_user_success == True:
log_message(user.id, update.message.text) log_message(user.id, update.message.text)
print("user added & message logged") print("user added & message logged")
else: else:
print("Something went wrong adding the user!") print("Something went wrong adding the user!")
# DB queries # DB queries
def id_exists(id_value): 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): for id1 in s.query(User.id).filter_by(id=id_value):
if id1: if id1:
bool_set = True bool_set = True
s.close() s.close()
return bool_set return bool_set
def log_message(user_id, user_message): def log_message(user_id, user_message):
@ -62,10 +62,10 @@ def log_message(user_id, user_message):
s.add(msg1) s.add(msg1)
s.commit() s.commit()
s.close() s.close()
except Exception as e: except Exception as e:
print(e) print(e)
def add_user(user_id, first_name, last_name, username): def add_user(user_id, first_name, last_name, username):
try: try:
s = session() s = session()
@ -74,15 +74,15 @@ def add_user(user_id, first_name, last_name, username):
s.add(user) s.add(user)
s.commit() s.commit()
s.close() s.close()
if id_exists(user_id) == True: if id_exists(user_id) == True:
bool_set = True bool_set = True
return bool_set return bool_set
except Exception as e: except Exception as e:
print(e) print(e)
def error(bot, update, error): def error(bot, update, error):
"""Log Errors caused by Updates.""" """Log Errors caused by Updates."""
@ -92,7 +92,7 @@ def error(bot, update, error):
def main(): def main():
"""Start the bot.""" """Start the bot."""
# Create the EventHandler and pass it your bot's token. # 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 # Get the dispatcher to register handlers
dp = updater.dispatcher dp = updater.dispatcher
@ -101,7 +101,7 @@ def main():
# on noncommand i.e message - echo the message on Telegram # on noncommand i.e message - echo the message on Telegram
dp.add_handler(MessageHandler(Filters.text, logger)) dp.add_handler(MessageHandler(Filters.text, logger))
# dp.add_handler(MessageHandler(Filters.status_update, status)) # dp.add_handler(MessageHandler(Filters.status_update, status))
# log all errors # log all errors

2
config.cnf.sample Normal file
View File

@ -0,0 +1,2 @@
[postgres]
postgres_url = postgresql://<username>:<password>@localhost:5432/<databasename>

View File

@ -1,22 +1,26 @@
from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func
from sqlalchemy.orm import relationship, backref from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base 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/ This model has been referenced from: https://www.pythoncentral.io/sqlalchemy-orm-examples/
''' '''
Base = declarative_base() Base = declarative_base()
class User(Base): class User(Base):
__tablename__ = 'users' __tablename__ = 'users'
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
first_name = Column(String) first_name = Column(String)
last_name = Column(String) last_name = Column(String)
username = Column(String) username = Column(String)
class Message(Base): class Message(Base):
__tablename__ = 'messages' __tablename__ = 'messages'
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
@ -26,12 +30,13 @@ class Message(Base):
# of an Employee to be the current time when an # of an Employee to be the current time when an
# Employee record was created # Employee record was created
time = Column(DateTime, default=func.now()) time = Column(DateTime, default=func.now())
from sqlalchemy import create_engine from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:<password>@localhost:5432/origindb') engine = create_engine(postgres_url)
from sqlalchemy.orm import sessionmaker from sqlalchemy.orm import sessionmaker
session = sessionmaker() session = sessionmaker()
session.configure(bind=engine) session.configure(bind=engine)
Base.metadata.create_all(engine) Base.metadata.create_all(engine)
print "Created database model"

View File

@ -1,3 +1,4 @@
psycopg2==2.7.3.2 psycopg2==2.7.3.2
python-telegram-bot==9.0.0 python-telegram-bot==9.0.0
SQLAlchemy==1.2.2 SQLAlchemy==1.2.2
configparser==3.5.0