Emir Hanic
Published

Mixtile Edge 2 Kit – Air Quality Telegram Bot

In the following post, I will try to accurately describe the process of the Telegram bot creation powered by the Mixtile Edge 2 Kit.

BeginnerFull instructions provided6 hours69
Mixtile Edge 2 Kit – Air Quality Telegram Bot

Things used in this project

Hardware components

Mixtile Edge 2 Kit
×1

Software apps and online services

Telegram
Snappy Ubuntu Core
Snappy Ubuntu Core

Story

Read more

Code

database.oy

Python
import sqlite3
import schedule
import time
from datetime import datetime

#Import scrapers
import scraper

# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('airQ.db')
c = conn.cursor()

# Create a table if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS data
             (timestamp TEXT, SarA REAL, SarB REAL, SarC REAL)''')

def store_data():
    # Example data to store
    value = [scraper.Sarajevo().bjelave_pm25, scraper.Sarajevo().vogosca_pm25, scraper.Sarajevo().otoka_pm25]
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
    # Insert data into the table
    c.execute("INSERT INTO data (timestamp, SarA, SarB, SarC) VALUES (?, ?, ?, ?)", (timestamp, value[0], value[1], value[2]))
    conn.commit()
    print("Data stored at " + timestamp)

# Schedule the store_data function to run every hour
schedule.every().minute.do(store_data)

print("Starting the scheduler...")

# Keep the script running
while True:
    schedule.run_pending()
    time.sleep(1)

main.py

Python
import os
from dotenv import load_dotenv
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, CallbackContext, CallbackQueryHandler

#Import scrapers
import sqlite3

# Load environment variables from the .env file, searching up parent directories
load_dotenv()

# Access environment variables using os.environ
TOKEN = os.environ.get('TOKEN')
BOT_USERNAM = os.environ.get('BOT_USERNAME')

#Database connection
conn = sqlite3.connect('airQ.db')
c = conn.cursor()

c.execute('SELECT * FROM data ORDER BY rowid DESC LIMIT 1')

last_row = c.fetchone()

conn.close()

dateTime = last_row[0]
bjelave_pm25 = last_row[1]
vogosca_pm25 = last_row[2]
otoka_pm25 = last_row[3]

#COMMANDS
async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    await update.message.reply_text('Hello! I am AirQuality BOT. All necessary information can be found here')


#Sarajevo
async def sarajevo_pm25_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
        await update.message.reply_text(f'''Current value of PM2.5 paricles in Sarajevo at {dateTime}:\n
        Bjelave: {bjelave_pm25} µg/m3\n
        Vogošća: {vogosca_pm25} µg/m3\n
        Otoka: {otoka_pm25} µg/m3\n
                                    ''')

if __name__ == '__main__':
    print('Bot is working...')
    app = Application.builder().token(TOKEN).build()

    #commands
    app.add_handler(CommandHandler('start', start_command))

    app.add_handler(CommandHandler('sarajevo25', sarajevo_pm25_command))
    
    print('Polling...')
    app.run_polling(poll_interval=3)

scraper.py

Python
import bs4
import requests
import os
from dotenv import load_dotenv

load_dotenv()

# Access environment variables using os.environ
url = os.environ.get('FHMZBIH')

AQ_value = requests.get(url)
AQ_value_soup = bs4.BeautifulSoup(AQ_value.text, 'lxml')

i = 0
with open('index.html', 'w') as f:
    for x in AQ_value_soup.select('tr td'):
        f.write(str(i)+" "+str(x) + "\n")
        i = i+1

class Sarajevo:
    def __init__(self):
        AQ_value = requests.get(url)
        AQ_value_soup = bs4.BeautifulSoup(AQ_value.text, 'lxml')
        self.bjelave_pm25 = AQ_value_soup.select('tr td')[27].text
        self.otoka_pm25 = AQ_value_soup.select('tr td')[52].text
        self.vogosca_pm25 = AQ_value_soup.select('tr td')[68].text

requirements.txt

Python
beautifulsoup4==4.12.2
bs4==0.0.1
python-telegram-bot==20.8
lxml==4.9.3
requests==2.31.0
python-dotenv==1.0.1
schedule==1.2.2

Credits

Emir Hanic
1 project • 1 follower
Contact

Comments

Please log in or sign up to comment.