├── dbsample.py ├── dbhelper.py └── telebot.py /dbsample.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | class DBHelper: 3 | def __init__(self, dbname="todo.sqlite"): 4 | self.dbname = dbname 5 | self.conn = sqlite3.connect(dbname) 6 | 7 | def setup(self): 8 | # create table with tablename items 9 | stmt = "CREATE _____ IF NOT EXISTS items (description ___)" 10 | self.conn.execute(stmt) 11 | self.conn.commit() 12 | 13 | def add_item(self, item_text): 14 | stmt = "_____ INTO items VALUES (?)" 15 | args = (item_text, ) 16 | self.conn.execute(stmt, args) 17 | self.conn.commit() 18 | 19 | def delete_item(self, item_text): 20 | stmt = "DELETE FROM items WHERE _______" 21 | args = (item_text, ) 22 | self.conn.execute(stmt, args) 23 | self.conn.commit() 24 | 25 | def get_items(self): 26 | stmt = "SELECT _____ FROM ____" 27 | # To retrieve data after executing a SELECT statement, treat the cursor as an iterator.refer to docs for other methods. 28 | # row is returned as a tuple of the column values, hence select the data by using x[0] 29 | return [x[0] for x in self.conn.execute(stmt)] 30 | 31 | def check_exists(self, item_text): 32 | stmt = "_____ description FROM items WHERE description = (?)" 33 | args = (item_text, ) 34 | return [x[0] for x in self.conn.execute(stmt,args)] 35 | -------------------------------------------------------------------------------- /dbhelper.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | class DBHelper: 3 | def __init__(self, dbname="todo.sqlite"): 4 | self.dbname = dbname 5 | self.conn = sqlite3.connect(dbname) 6 | 7 | def setup(self): 8 | # create table with tablename items 9 | stmt = "CREATE TABLE IF NOT EXISTS items (description text)" 10 | self.conn.execute(stmt) 11 | self.conn.commit() 12 | 13 | def add_item(self, item_text): 14 | stmt = "INSERT INTO items VALUES (?)" 15 | args = (item_text, ) 16 | self.conn.execute(stmt, args) 17 | self.conn.commit() 18 | 19 | def delete_item(self, item_text): 20 | stmt = "DELETE FROM items WHERE description = (?)" 21 | args = (item_text, ) 22 | self.conn.execute(stmt, args) 23 | self.conn.commit() 24 | 25 | def get_items(self): 26 | stmt = "SELECT description FROM items" 27 | # To retrieve data after executing a SELECT statement, treat the cursor as an iterator.refer to docs for other methods. 28 | # row is returned as a tuple of the column values, hence select the data by using x[0] 29 | return [x[0] for x in self.conn.execute(stmt)] 30 | 31 | def check_exists(self, item_text): 32 | stmt = "SELECT description FROM items WHERE description =(?)" 33 | args = (item_text, ) 34 | return [x[0] for x in self.conn.execute(stmt,args)] 35 | -------------------------------------------------------------------------------- /telebot.py: -------------------------------------------------------------------------------- 1 | # urllib requires python3 2 | import json 3 | import requests 4 | import time 5 | import urllib 6 | from dbhelper import DBHelper 7 | 8 | db = DBHelper() 9 | 10 | TOKEN = "" 11 | URL = "https://api.telegram.org/bot{}/".format(TOKEN) 12 | 13 | #get url downloads content from url 14 | def get_url(url): 15 | response = requests.get(url) 16 | content = response.content.decode("utf8") 17 | return content 18 | 19 | #gets string response from def(get_url) and parses it into a python dictionary 20 | def get_json_from_url(url): 21 | content = get_url(url) 22 | js = json.loads(content) 23 | return js 24 | 25 | #uses previous two functions but only for retrieving updates, which can be done through specification in url 26 | def get_updates(offset=None): 27 | url = URL + "getUpdates" 28 | #to understand how offset helps us get the latest msg from the server, read about longpolling. 29 | if offset: 30 | url += "?offset={}".format(offset) 31 | js = get_json_from_url(url) 32 | return js 33 | 34 | def get_last_update_id(updates): 35 | update_ids = [] 36 | for update in updates["result"]: 37 | update_ids.append(int(update["update_id"])) 38 | return max(update_ids) 39 | 40 | def handle_updates(updates): 41 | for update in updates["result"]: 42 | text = update["message"]["text"] #returns telegram text message 43 | chat = update["message"]["chat"]["id"] #returns telegram msd sender's id 44 | #switch to check for cmds in telegram message 45 | print(text[0:8]) 46 | if text == "/start": 47 | send_message("Welcome to itemListBot.", chat) 48 | elif ("/additem" in text) and (text[0:8] == "/additem"): 49 | #breaks up message into msg to add to todo list 50 | itemName = text[9:] 51 | db.add_item(itemName) 52 | elif ("/removeitem" in text) and (text[0:11]== "/removeitem"): 53 | itemName = text[12:] 54 | if db.check_exists(itemName)==[]: 55 | send_message("item not in cart.", chat) 56 | else: 57 | db.delete_item(itemName) 58 | elif text == "/entries": 59 | entry_msg = "" 60 | itemList = db.get_items() 61 | print(itemList) 62 | #concatenate itemList 63 | for i in range(len(itemList)): 64 | entry_msg+=itemList[i] +'\n' 65 | send_message(entry_msg,chat) 66 | elif text == "/itemListLength": 67 | lenItemList = len(db.get_items()) 68 | send_message(lenItemList,chat) 69 | else: 70 | send_message("not a cmd", chat) 71 | 72 | #gets content and sender id of last message in telegram 73 | def get_last_chat_id_and_text(updates): 74 | num_updates = len(updates["result"]) 75 | last_update = num_updates - 1 76 | text = updates["result"][last_update]["message"]["text"] 77 | chat_id = updates["result"][last_update]["message"]["chat"]["id"] 78 | return (text, chat_id) 79 | 80 | #uses sendMessageAPI cmd to send text and chat ID as url parameters 81 | def send_message(text, chat_id, reply_markup=None): 82 | text = urllib.parse.quote_plus(text) 83 | url = URL + "sendMessage?text={}&chat_id={}&parse_mode=Markdown".format(text, chat_id) 84 | if reply_markup: 85 | url += "&reply_markup={}".format(reply_markup) 86 | get_url(url) 87 | 88 | 89 | def main(): 90 | #setup database 91 | db.setup() 92 | last_update_id = None 93 | #checks for new updates every 0.5 seconds 94 | while True: 95 | updates = get_updates(last_update_id) 96 | if len(updates["result"]) > 0: 97 | last_update_id = get_last_update_id(updates) + 1 98 | handle_updates(updates) 99 | time.sleep(0.5) 100 | 101 | #import functions into another script without running anything 102 | if __name__ == '__main__': 103 | main() --------------------------------------------------------------------------------