-
Notifications
You must be signed in to change notification settings - Fork 0
/
TelegramBotForAstoneshi.py
173 lines (139 loc) · 4.94 KB
/
TelegramBotForAstoneshi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# -*- coding: utf-8 -*-
"""TelegramBotForAstoneshi.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ggZkgzdYXiJ4uUY2dmib15Or4tvp9FvR
# Telegram Bot
Simple Bot to save incoming messages.
You will find it at https://**t**.me/messagecollector_bot
"""
!pip install python-telegram-bot==12.7 pymongo dnspython==2.0.0 pyTelegramBotAPI==4.0.1 pandas jsonpickle
# importing all dependancies
import logging
import os
import telebot
from telegram import ParseMode
from telegram.ext import CallbackContext, Updater, CommandHandler, JobQueue, Dispatcher
import pymongo
import json
import pandas as pd
import jsonpickle
#Override environment variables on dev environment if you test the bot
# Getting environment variables from Heroku configs if not overriden
BOT_TELEGRAM_API_TOKEN = os.environ.get('botKey', "2041101413:AAHXZ4YS9hQY0tQa-s_i8fCT4az1SYa89ZI")
BOT_MONGODB_CONECTION_URL = os.environ.get('mongodbConnectionURL', "mongodb+srv://botaUser:botaPassword@botscluster.j5qlm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority")
BOT_DATABASE_NAME = os.environ.get('databaseName', "TelegramBotForAstoneshi")
# Initialize logging for debugging purpose
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s',level=logging.INFO)
logger = logging.getLogger(__name__)
# Database Class
class Database:
# constructor
def __init__(self):
self.connectionURL = BOT_MONGODB_CONECTION_URL
self.databaseName = BOT_DATABASE_NAME
self.dbClient = None
# connect to the database
def connect(self):
try:
if not self.dbClient:
logger.info("Database Client initialized.")
self.dbClient = pymongo.MongoClient(self.connectionURL)
database = self.dbClient[str(self.databaseName)]
if database:
logger.info("Database Connected.")
return database
else:
logger.info("Database Connection failed.")
return None
else:
logger.info("Database Client Connection failed.")
return None
except Exception as er:
logger.error(er)
# Message Class
class Message:
# message constructor
def __init__(self, dbConnection):
self.dbConnection = dbConnection
# save message object
def save_message(self, messageObj):
try:
if self.dbConnection:
self.messagesCollection = self.dbConnection["messages"]
if self.messagesCollection.insert_one(messageObj):
logger.info("Message saved in Database")
return True
else:
logger.error("Failed to save message on database")
return False
else:
logger.error("Database connection error")
return False
except Exception as er:
logger.error(er)
return False
# Initializing database
db = Database()
dbConnection = db.connect()
# Initializing a message object
messageContent = Message(dbConnection)
# initialize the bot
bot = telebot.TeleBot(BOT_TELEGRAM_API_TOKEN, parse_mode="markdown")
# Function to catch incomming command /about
@bot.message_handler(commands=['about'])
def about(message):
try:
bot.reply_to(message, "This is a sample Telegram bot. This bot will store incoming messages in a database")
except Exception as e:
logger.error(e)
pass
# Function to catch incomming command /help
@bot.message_handler(commands=['help'])
def help(message):
try:
bot.reply_to(message, "Send a message. Then have a look https://github.com/w3gen/TelegramBotForAstoneshi")
except Exception as e:
logger.error(e)
pass
# catch all messages and save in database
@bot.message_handler(func=lambda m: True)
def echo_all(message):
try:
#bot.reply_to(message, message.text)
messageObj = {
"chat_id": message.chat.id,
"message_id": message.message_id,
"date": message.date,
"type": message.chat.type,
"text": message.text,
"user": message.from_user.id,
"username": message.from_user.username,
"first_name": message.from_user.first_name,
"last_name": message.from_user.last_name
}
messageContent.save_message(messageObj)
except Exception as e:
logger.error(e)
pass
# this function will send a message to a specific chat ID
def sendMessageViaChatId(chat_id, txt):
bot.send_message(chat_id, txt)
sendMessageViaChatId(-1001545752396, "Hi") # 1664758714 is the chat ID (For private messages, group ID = Chat ID)
# start polling to continuously listen for messages
bot.polling()
# gracefully stop the bot after ctrl + c
bot.stop_polling()
"""
---
# View Data
View collected data from the Bot. (First stop the bot to view data)"""
def viewData():
# getting database connection
messagesCollection = dbConnection["messages"]
# Make a query to the specific DB and Collection
cursor = messagesCollection.find()
# Expand the cursor and construct the DataFrame
df = pd.DataFrame(list(cursor))
return df
viewData()