Machine Learning with Python
68.6K subscribers
1.56K photos
136 videos
200 files
1.31K links
Learn Machine Learning with hands-on Python tutorials, real-world code examples, and clear explanations for researchers and developers.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
This media is not supported in your browser
VIEW IN TELEGRAM
🖥 Want your Telegram bot to respond using ChatGPT?

Do it in a couple of minutes: just install the python-telegram-bot library, add your #OpenAI #API key and bot token, and the bot will start replying to all messages using #ChatGPT.

from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes
from openai import OpenAI


Specify your keys
OPENAI_API_KEY = "sk-..." 
TELEGRAM_TOKEN = "123456789:ABC..."

client = OpenAI(api_key=OPENAI_API_KEY)

async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
    user_text = update.message.text

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": user_text}]
    )

    await update.message.reply_text(response.choices[0].message.content)

app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()


https://xn--r1a.website/CodeProgrammer 👍
Please open Telegram to view this post
VIEW IN TELEGRAM
❤11👍2💯1
#TelegramBot #Python #SQLite #DataExport #CSV #API

Lesson: Creating a Telegram Bot to Export Channel Members to a CSV File

This tutorial guides you through building a Telegram bot from scratch. When added as an administrator to a channel, the bot will respond to an /export command from the channel owner, exporting the list of members (Username, User ID, etc.) to a CSV file and storing a log of the action in a SQLite database.

IMPORTANT NOTE: Due to Telegram's privacy policy, bots CANNOT access users' phone numbers. This field will be marked as "N/A".

---

#Step 1: Bot Creation and Project Setup

First, create a bot via the @BotFather on Telegram. Send it the /newbot command, follow the instructions, and save the HTTP API token it gives you.

Next, set up your Python environment. Install the necessary library: python-telegram-bot.

pip install python-telegram-bot


Create a new Python file named bot.py and add the basic structure. Replace 'YOUR_TELEGRAM_API_TOKEN' with the token you got from BotFather.

import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes

# Enable logging
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)

TOKEN = 'YOUR_TELEGRAM_API_TOKEN'

def main() -> None:
"""Start the bot."""
application = Application.builder().token(TOKEN).build()

# We will add command handlers here in the next steps
# application.add_handler(CommandHandler("export", export_members))

print("Bot is running...")
application.run_polling()

if __name__ == "__main__":
main()

# Hashtags: #Setup #TelegramAPI #PythonBot #BotFather


---

#Step 2: Database Setup for Logging (database.py)

To fulfill the requirement of using a database, we will log every export request. Create a new file named database.py. This separates our data logic from the bot logic.

import sqlite3
from datetime import datetime

DB_NAME = 'bot_logs.db'

def setup_database():
"""Creates the database table if it doesn't exist."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS export_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
chat_title TEXT,
requested_by_id INTEGER NOT NULL,
requested_by_username TEXT,
timestamp TEXT NOT NULL
)
''')
conn.commit()
conn.close()

def log_export_action(chat_id, chat_title, user_id, username):
"""Logs a successful export action to the database."""
conn = sqlite3.connect(DB_NAME)
cursor = conn.cursor()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cursor.execute(
"INSERT INTO export_logs (chat_id, chat_title, requested_by_id, requested_by_username, timestamp) VALUES (?, ?, ?, ?, ?)",
(chat_id, chat_title, user_id, username, timestamp)
)
conn.commit()
conn.close()

# Hashtags: #SQLite #DatabaseDesign #Logging #DataPersistence


---

#Step 3: Implementing the Export Command and Permission Check

Now, we'll write the core function in bot.py. This function will handle the /export command. The most crucial part is to check if the user who sent the command is the creator of the channel. This prevents any admin from exporting the data.
❤5
🚀 RESEARCH & DIGITAL SOLUTIONS — YOUR PARTNER IN SUCCESS!
Are you a researcher, student, business owner, or developer looking for professional support? We are here to help you turn your ideas into real results! 💡

🔬 1. Scientific Research & Academic Publishing
Professional review and evaluation of scientific manuscripts before submission.
Guidance on journal selection and publication strategies.
Expert advice to improve research quality and presentation.
Support for researchers throughout the academic publishing process.

💻 2. Website & Software Development
Professional website design and development for businesses and individuals.
Custom electronic systems tailored to your needs.
Technical assistance for students and academic projects.

⚙️ 3. API & User Interface (UI) Services
API development and integration.
Modern, responsive, and user-friendly interface design.
Seamless integration between applications and systems.

📊 4. Real-World & Synthetic Datasets
Providing real-world datasets for research and analysis.
Creating customized synthetic datasets according to your requirements.
Data support for scientific research, machine learning, and AI projects.

🤝 5. FREE Discussion & Consultation
Discuss your research ideas and technical projects with us.
Get initial guidance and recommendations.
Explore the best solutions for your academic or professional needs.

🌟 WHY CHOOSE US?
✅ Research and technology expertise in one place.
✅ Tailored solutions based on your needs.
✅ Professional guidance and practical support.
✅ Free initial discussion and consultation.

📩 CONTACT US ON TELEGRAM
👨‍💻 Team Admin & Support: @Omidyzd62
💬 Feel free to contact us to discuss your ideas, ask questions, or explore how we can help!
Your Research. Your Ideas. Our Expertise. Your Success. 🎯

#ResearchSupport #AcademicPublishing #ScientificResearch #WebDevelopment #SoftwareDevelopment #API #UIUX #Datasets #MachineLearning #ArtificialIntelligence #StudentSupport
❤3👍1💯1