Development process #selfdevelopmentclub - 26/02

in hive-146361 •  2 years ago 

How to overcome stagnation an (3).png

This code defines a Telegram bot using the Telebot library in Python. The bot interacts with users by receiving messages and processing them based on their content. The bot connects to a SQLite database and performs CRUD operations to store and retrieve data.

Work Version botSDC1.py


import sqlite3
from sqlite3 import Error
import telebot
import sys
from telebot import types # для указание типов
from telebot.types import LabeledPrice, ShippingOption
from steem import Steem
from datetime import datetime, timedelta
import re

def create_connection():
    conn = None
    try:
        conn = sqlite3.connect('newsdc.db')
        print('Connection to SQLite DB successful')
    except Error as e:
        print(f"The error '{e}' occurred")

    return conn
import sqlite3
from sqlite3 import Error
import telebot
import sys
from telebot import types # to specify types
from telebot.types import LabeledPrice, ShippingOption
from steem import Steem
from datetime import datetime, timedelta
import re

# Create a database connection
def create_connection():
     conn = None
     try:
         conn = sqlite3.connect('newsdc.db')
         print('Connection to SQLite DB successful')
     except Error as e:
         print(f"The error '{e}' occurred")

     return conn

# Check if an entry exists in the users table
def check_user_exists(conn, user_id):
     c = conn.cursor()
     c.execute("SELECT * FROM users WHERE user_id = ?", (user_id,))
     return c.fetchone() is not None

# define a function to handle the RATING button
def handle_rating_button(user_id):
     # Create a database connection
     conn = create_connection()
     if conn is None:
         print("Error: Failed to create database connection")
         return
     c = conn.cursor()
     c.execute('SELECT * FROM comments ORDER BY comment DESC')
     results = c.fetchall()
     conn.close()
     rating = '\n'.join([f'{row[0]}. {row[1]}: {row[2]}' for row in results])
     bot.send_message(user_id,rating)
    
def get_link_by_user_id(conn, user_id):
     c = conn.cursor()
     c.execute("SELECT link FROM users WHERE user_id = ?", (user_id,))
     result = c.fetchone()
     if result is None:
         print(f"No link found for user {user_id}")
         bot.send_message(user_id,
                      "Please send your STEEMIT account name to the bot so that it remembers you. Thank you!")
         return None
     else:
         print(f"Link for user {user_id}: {result[0]}")
         bot.send_message(user_id,
                      f"You STEEMIT account: {result[0]}")
         return result[0]
                     
# Add a new record to the users table
def add_user_link(conn, user_id, link):
     # Convert to lowercase
     link = link.lower()

     # Remove spaces
     link = link.replace(" ", "")

     # Remove special characters
     link = re.sub('[^A-Za-z0-9]+', '', link)
     c = conn.cursor()
     c.execute('''INSERT INTO users (user_id, link)
                  VALUES (?, ?)''', (user_id, link))
     conn.commit()
     print(f"User {user_id} link added successfully")
     bot.send_message(user_id,
                      "Thank you. You name of STEEMIT account added successfully")

# Initialize the bot
bot = telebot.TeleBot('xxx:AAF-xxx')

# Handler for the /delete command
def count_com(conn,acc_name):
     account_name = acc_name
     account_name = str(get_link_by_user_id(conn,acc_name))

     s = Steem()

     # Calculate the date "yesterday"
     yesterday = datetime.now() - timedelta(days=1)
    
    
     bot.send_message(acc_name, account_name)
     # Get all user comments
     comments = s.get_discussions_by_comments({"start_author": account_name, "limit":100})

     count = 0

     for comments in comments:
         created = datetime.strptime(comment["created"], "%Y-%m-%dT%H:%M:%S")
         if created > yesterday:
             count += 1
             #print(comment["body"])
   
    # Check if there is an entry in the table before adding
     c = conn.cursor()
     c.execute("SELECT COUNT(*) FROM comments WHERE user_id = ?", (account_name,))
     row_count = c.fetchone()[0]
     if row_count > 0:
         print(f"Comments already counted for user {account_name}")
         bot.send_message(acc_name, "Comments already counted for you yesterday")
     else:
         c = conn.cursor()
         c.execute('''INSERT INTO comments (user_id, comment) VALUES (?, ?)''', (account_name, count))
         conn.commit()
    
     print("Number of comments yesterday: ", count)
     count_message = "Number of comments yesterday: " + str(count)
     bot.send_message(acc_name,
                      count_message)
                     
#@bot.message_handler(commands=['delete'])
def handle_delete(message):
     conn = create_connection()
     if conn is None:
         print("Error: Failed to create database connection")
         return
        
     # Delete the record from the users table with the telegram ID of the current user
     c = conn.cursor()
     c.execute('''DELETE FROM users
                  WHERE user_id = ?''', (message.from_user.id,))
     conn.commit()
     bot.reply_to(message, 'You have removed the link to your STEEMIT account! Please send your STEEMIT account name to the bot so that it remembers you. Thank you!')

@bot.message_handler(commands=['start'])
def start(message):
    who_enter = str(message.chat.id)+" name: "+str(message.chat.username)
    bot.send_message('221901211',who_enter)
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("🔥 UNLINK")
    btn2 = types.KeyboardButton("✅ COUNT")
    btn3 = types.KeyboardButton("👑 TOP RANK")
    #btn4 = types.KeyboardButton("Contacts/help")
    #btn5 = types.KeyboardButton("About us")
    markup.add(btn1, btn2, btn3)
    bot.send_message(message.chat.id, text='Hello {0.first_name}! I am a bot for the "#selfdevelopmentclub" project, sent to the project description: https://steemit.com/hive-153970/@alexmove/once-again-about-self-development-club. It turns out we can already count a lot of benefits: STUDY, BLOGGING, DATING, and, of course, the opportunity to receive a reward, EARN.: @alexmove12345'.format(message.from_user), reply_markup=markup)
    conn = create_connection()
    if conn is None:
        print("Error: Failed to create database connection")
        return
    
    if check_user_exists(conn, message.from_user.id):
        get_link = str(get_link_by_user_id(conn,message.chat.id))+"Your STEEMIT account:"
    else:
        bot.send_message(message.chat.id,
                     "Please send your STEEMIT account name to the bot so that it remembers you. Thank you!")
      
    conn.close()
    
@bot.message_handler(func=lambda message: True)
def handle_message(message):
    conn = create_connection()
    if conn is None:
        print("Error: Failed to create database connection")
        return

    if(message.text == "🔥 UNLINK"):
        handle_delete(message)        
    elif(message.text == "✅ COUNT"): 
        if not check_user_exists(conn,message.from_user.id):
            bot.send_message(message.chat.id, "Please send your STEEMIT account name to the bot so that it remembers you. Thank you!")
        else:
            conn = create_connection()
            if conn is None:
                print("Error: Failed to create database connection")
                return
            else:
                count_com(conn,message.chat.id)
                         
    elif(message.text == "👑 TOP RANK"):
        #bot.send_message(message.chat.id,
                    # 'You press 👑 TOP RANK')
        handle_rating_button(message.chat.id)                     
        
    else:
        conn = create_connection()
        if conn is None:
            print("Error: Failed to create database connection")
            return
        
        if not check_user_exists(conn, message.from_user.id):
            add_user_link(conn, message.from_user.id, message.text)
        else:
            print(f"User {message.from_user.id} link already exists in database")
            bot.send_message(message.chat.id,
                     'Your STEEMIT account name is already saved in the database, thanks. Now you can use the ✅ COUNT button to count your comments for yesterday. And "👑 TOP RANK to view the rating. Thank you. ')         
        conn.close()


bot.polling()

Thank you for your attention, and have a good day.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!