collect users data on telegram bot new

PHOTO EMBED

Thu Nov 16 2023 23:23:40 GMT+0000 (Coordinated Universal Time)

Saved by @joeclaap #telegram #bot #user #info #collect #store #json

import json
from telegram import Update
from telegram.ext import CallbackContext

def append_user_info_to_json(update: Update, context: CallbackContext, file_path='users.json'):
    user_info = {
        'chat_id': update.effective_chat.id,
        'first_name': update.effective_chat.first_name,
        'last_name': update.effective_chat.last_name,
        'username': update.effective_chat.username
    }

    try:
        # Load existing data
        with open(file_path, 'r') as file:
            data = json.load(file)
    except FileNotFoundError:
        # If the file doesn't exist, start a new list
        data = []

    # Append new data
    data.append(user_info)

    # Write updated data back to file
    with open(file_path, 'w') as file:
        json.dump(data, file, indent=4)


def start(update: Update, context: CallbackContext) -> None:
    # Append user info to JSON
    append_user_info_to_json(update, context)
content_copyCOPY