-
Notifications
You must be signed in to change notification settings - Fork 1
/
Main.py
112 lines (89 loc) · 3.43 KB
/
Main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Eduardo Peluffo"
import json
import logging as log
import random
import re
from random import randrange, choice
from time import sleep
from uuid import uuid4
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode, Update, \
InlineQueryResultArticle, InputTextMessageContent
from telegram.ext import (InlineQueryHandler, Updater, CommandHandler, \
CallbackQueryHandler, MessageHandler, Filters, CallbackContext)
from telegram.utils.helpers import mention_html, escape_markdown
import asyncio
import traceback
import sys
import os
import configparser
from multiprocessing import Process
from telethon import TelegramClient, events, types, functions, Button
from telethon.sessions import StringSession
# Configuracion para logeo de datos en Heroku
log.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=log.INFO)
logger = log.getLogger(__name__)
# 1 - Cargo variables de entorno
API_ID = os.environ.get('api_id', None)
API_HASH = os.environ.get('api_hash', None)
STRING_SESSION = os.environ.get('STRING_SESSION', None)
BOT_TOKEN = os.environ.get('bot_token', None)
# 2 - Si no estan las obtengo del config, esto lo uso para probar local
if API_ID is None or API_HASH is None:
config = configparser.ConfigParser()
config.read('init.ini')
if config.has_section('ENVIROMENT'):
API_ID = int(config['ENVIROMENT']['TG_API_ID'])
API_HASH = config['ENVIROMENT']['TG_API_HASH']
STRING_SESSION = config['ENVIROMENT']['STRING_SESSION']
BOT_TOKEN = config['ENVIROMENT']['BOT_TOKEN']
#--------------------------------- BOT --------------------------------------
def command_start(update: Update, context: CallbackContext):
bot = context.bot
cid = update.message.chat_id
bot.send_message(cid, "Bot para aprender")
def bot_main():
updater = Updater(BOT_TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", command_start))
updater.start_polling(timeout=30)
updater.idle()
#-------------------------------FIN BOT ------------------------------------
#------------------------------ USER BOT -----------------------------------
# Esto hace que escuche en "Mensajes guardados" y solo mensajes mios (outgoing)
@events.register(events.NewMessage(chats='me', outgoing=True))
async def me_handler(event):
# Logeo en Heroku que mensaje entro.
logger.info(f"New message {event.raw_text}")
# Que cuenta de telegram recibio el mensaje? La obtengo.
client = event.client
# El mensaje decia "Hola"?
if event.raw_text == 'Hola':
# Entonces respondo ¿Cómo estas?
await client.send_message('me', '¿Cómo estas?')
# El mensaje decia "Todo bien"?
if event.raw_text == 'Todo bien':
# Entonces respondo ¿Me alegro?
await client.send_message('me', 'Me alegro')
client1 = None
if API_ID and API_HASH and STRING_SESSION:
client1 = TelegramClient(StringSession(STRING_SESSION), API_ID, API_HASH)
# Agrego al cliente la capacidad de escuchar los mensajes de "Mensajes guardados"
client1.add_event_handler(me_handler)
#------------------------------ FIN USER BOT -------------------------------
# Configuro para que se puede usar el bot y el user bot al mismo tiempo.
def loop_a():
while 1:
sleep(0.01)
client1.start()
def loop_b():
while 1:
bot_main()
if __name__ == '__main__':
if client1 is not None:
p1 = Process(target=loop_a).start()
if BOT_TOKEN is not None:
p2 = Process(target=loop_b).start()