Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BOT-TELEGRAM POLLING -> WEBHOOK #11801

Closed
Hugo-Qc opened this issue Dec 27, 2024 · 2 comments
Closed

BOT-TELEGRAM POLLING -> WEBHOOK #11801

Hugo-Qc opened this issue Dec 27, 2024 · 2 comments

Comments

@Hugo-Qc
Copy link

Hugo-Qc commented Dec 27, 2024

I am new to programming and have created a Telegram bot. Can someone guide or help me convert this mess into a webhook to run on Render? Thank you!
import logging
from telegram import Update
from telegram.ext import Application, MessageHandler, filters, CallbackContext
import nest_asyncio
import asyncio
import re

logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.WARNING
)
logger = logging.getLogger(name)

API_TOKEN = '7157668153:.....'
current_sequence = {'A': 1, 'B': 1, 'D': 1, 'E': 1, 'G': 1}
identifier_char = 'B' # Giá trị mặc định ban đầu

processed_accounts = set()
group_message_store = {}

def update_sequence(prefix: str, current_seq: int) -> str:
return f"{prefix}{current_seq}"

async def reset_sequence(update: Update, context: CallbackContext) -> None:
global current_sequence
prefix = update.message.text.strip().upper()
if prefix in current_sequence:
current_sequence[prefix] = 1
await update.message.reply_text(f"{prefix} đã được reset về 1")
else:
await update.message.reply_text("Vui lòng nhập một ký tự từ A, B, D, E, hoặc G.")

async def filter_message(update: Update, context: CallbackContext) -> None:
global identifier_char, current_sequence
text = update.message.text
messages = text.split('\n\n') # Split the messages by double newlines

current_group_name = None
filtered_messages = []
group_start_seq = current_sequence[identifier_char]  # Track the start of sequence for the group

for idx, message in enumerate(messages, start=1):
    info = {}
    
    group_name_search = re.search(r'(Nhóm \d+ .*组)', message, re.IGNORECASE)
    if group_name_search:
        if current_group_name:  # If switching to a new group, finalize the previous group
            end_seq = current_sequence[identifier_char] - 1
            group_name_modified = f"{current_group_name} {identifier_char}{group_start_seq}-{end_seq}"
            await update.message.reply_text(group_name_modified)
            
            for msg in filtered_messages:
                await update.message.reply_text(msg)
            
            filtered_messages = []
            group_start_seq = current_sequence[identifier_char]

        current_group_name = group_name_search.group().strip()

    ten_nguoi_nhan_match = re.search(r'(收款人|款人|收款)\s*[::]?\s*([^\n]+)', message)
    if ten_nguoi_nhan_match:
        info['收款人'] = ten_nguoi_nhan_match.group(2).strip()

    so_tai_khoan_match = re.search(r'(账户|stk|Tài khoản ngân hàng)\s*[::]?\s*([^\n]+)', message)
    if so_tai_khoan_match:
        info['账户'] = so_tai_khoan_match.group(2).strip()

    ngan_hang_match = re.search(r'(银行|行)\s*[::]?\s*([^\n]+)', message)
    if ngan_hang_match:
        info['银行'] = ngan_hang_match.group(2).strip()

    so_tien_match = re.search(r'(金额|Số tiền)\s*[::]?\s*([^\n]+)', message)
    if so_tien_match:
        info['金额'] = so_tien_match.group(2).strip()

    noi_dung_match = re.search(r'(汇款内容|容|内容)\s*[::]?\s*([^\n]+)', message)
    if noi_dung_match:
        info['汇款内容'] = noi_dung_match.group(2).strip()

    if info:
        seq = update_sequence(identifier_char, current_sequence[identifier_char])
        current_sequence[identifier_char] += 1  # Increment the sequence for the identifier
        filtered_message = (
            f"{seq} 收款人:{info.get('收款人', '')}\n"
            f"账户:{info.get('账户', '')}\n"
            f"银行:{info.get('银行', '')}\n"
            f"金额:{info.get('金额', '130.000')}\n"
            f"汇款内容:{info.get('汇款内容', 'Ho tro du an')}"
        )
        filtered_messages.append(filtered_message)

if current_group_name and filtered_messages:
    end_seq = current_sequence[identifier_char] - 1
    group_name_modified = f"{current_group_name} {identifier_char}{group_start_seq}-{end_seq}"
    await update.message.reply_text(group_name_modified)

    for msg in filtered_messages:
        await update.message.reply_text(msg)

async def set_identifier(update: Update, context: CallbackContext) -> None:
global identifier_char
identifier_char = update.message.text.strip().upper()
if identifier_char in current_sequence:
await update.message.reply_text(f"Đã chuyển sang: {identifier_char}")
else:
await update.message.reply_text("Vui lòng nhập một ký tự từ A, B, D, E, hoặc G.")

async def update_current_sequence(update: Update, context: CallbackContext) -> None:
global current_sequence, identifier_char
text = update.message.text.strip().upper()

if len(text) >= 2 and text[0] in current_sequence and text[1:].isdigit():
    prefix = text[0]
    new_sequence = int(text[1:])
    identifier_char = prefix  # Cập nhật ký tự định danh hiện tại
    
    # Cập nhật số thứ tự hiện tại
    current_sequence[prefix] = new_sequence
    
    await update.message.reply_text(f"Bắt đầu từ: {prefix}{current_sequence[prefix]}")
else:
    await update.message.reply_text("Cú pháp không hợp lệ. Vui lòng gửi B4, D13, vv.")

async def main() -> None:
application = Application.builder().token(API_TOKEN).build()

application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND & filters.Regex('^[A-G]$'), set_identifier))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND & filters.Regex('^[A-G][0-9]+$'), update_current_sequence))
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND & ~filters.Regex('^[A-G][0-9]+$') & ~filters.Regex('^[A-G]$'), filter_message))

await application.run_polling(timeout=90)

if name == 'main':
nest_asyncio.apply()
asyncio.run(main())

@eshellman
Copy link
Collaborator

duplicate of #6263

@Hugo-Qc
Copy link
Author

Hugo-Qc commented Dec 28, 2024

duplicate of #6263

thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants