Cleaned up README and moved config info out of version control
Clarified naming of some things.
This commit is contained in:
parent
68cf51aa3e
commit
01019f1186
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal 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
|
39
README.md
39
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:<password>@localhost:5432/<databasename>')`
|
||||
- Run: `python model.py` to setup the DB tables, etc.
|
||||
- Run: `python bot.py` to start logger
|
||||
- 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://<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
30
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
|
||||
|
2
config.cnf.sample
Normal file
2
config.cnf.sample
Normal file
@ -0,0 +1,2 @@
|
||||
[postgres]
|
||||
postgres_url = postgresql://<username>:<password>@localhost:5432/<databasename>
|
25
model.py
25
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:<password>@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"
|
||||
|
@ -1,3 +1,4 @@
|
||||
psycopg2==2.7.3.2
|
||||
python-telegram-bot==9.0.0
|
||||
SQLAlchemy==1.2.2
|
||||
SQLAlchemy==1.2.2
|
||||
configparser==3.5.0
|
||||
|
Loading…
Reference in New Issue
Block a user