def __init__(self, chat_ids, token_bot, proxy_url=False):
     self.chat_ids = chat_ids
     if proxy_url:
         proxy = Request(proxy_url=proxy_url, con_pool_size=32)
         self.bot = bot.Bot(token = token_bot, request=proxy)
     else:            
         self.bot = bot.Bot(token = token_bot)
def ask(update: Update, unused: CallbackContext):
    if is_banned(
            str(update.message.chat.username) + "," +
            str(update.message.chat.id)):
        return
    if update.message.chat.username in users.keys(
    ) and time() - users[update.message.chat.username] <= 30:
        update.message.reply_text(
            "Errore, puoi fare una domanda ogni 30 secondi",
            parse_mode=ParseMode.MARKDOWN)
        return
    users[update.message.chat.username] = time()
    update.message.reply_text(
        "La tua domanda è stata notificata, presto riceverai una risposta",
        parse_mode=ParseMode.MARKDOWN)
    print(update.message.chat.username, "ha chiesto:", update.message.text)
    with open("admin.log", "r") as admin_log:
        for user in admin_log.readlines():
            user_id = user.split(",")[1]
            bot.Bot(bot_token.TOKEN).send_message(
                chat_id=user_id,
                text="Se devi bannare l'utente " +
                update.message.chat.username + "puoi usare /ban " +
                update.message.chat.username,
                parse_mode=ParseMode.MARKDOWN)
def main():
    updater = Updater(bot_token.TOKEN, use_context=True)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", bot_help))
    dp.add_handler(CommandHandler("ask", ask))
    dp.add_handler(CommandHandler("info", info))
    dp.add_handler(CommandHandler("beer", beer))
    dp.add_handler(CommandHandler("today", today))

    # admin function
    dp.add_handler(CommandHandler("ban", ban))

    # Invia Notifica a tutti i loggati (chiunque ha fatto start)
    with open("users.log", "r") as f:
        user_list = f.readlines()
        for user in user_list:
            user_id = user.split(",")[1]
            bot.Bot(bot_token.TOKEN).send_message(
                chat_id=user_id,
                text="Il meet inizierà a breve",
                parse_mode=ParseMode.MARKDOWN)

    print("Bot Started")
    updater.start_polling()
    updater.idle()
Пример #4
0
def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater(token)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    # for every message
    dp.add_handler(MessageHandler(Filters.text & Filters.group, asd_counter))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()
    t1 = threading.Thread(target=updater.idle)
    t2 = threading.Thread(target=notify_weekly(bot.Bot(token)))

    t1.start()
    t2.start()
Пример #5
0
def main():
    updater = Updater(token='205572739:AAEFs_y41exvonAdtj_ZHV9koxdzRrd7nz4')

    dispatcher = updater.dispatcher
    myBot = bot.Bot(token='205572739:AAEFs_y41exvonAdtj_ZHV9koxdzRrd7nz4')
    while True:
        myBot.sendMessage(updtext='Hi')
    updater.start_polling()
Пример #6
0
def respond():
    # retrieve the message in JSON and then transform it to Telegram object
    update = telegram.Update.de_json(request.get_json(force=True),
                                     bot.Bot(token=TOKEN))

    chat_id = update.message.chat.id
    msg_id = update.message.message_id

    # Telegram understands UTF-8, so encode text for unicode compatibility
    text_to_be_analyzed = update.message.text.encode('utf-8').decode()

    response = get_response(text_to_be_analyzed)
    bot.Bot(token=TOKEN).sendMessage(chat_id=chat_id,
                                     text=response,
                                     reply_to_message_id=msg_id)

    return 'ok'
Пример #7
0
def set_webhook():
    # bot.Bot(token = TOKEN).start_webhook(listen="0.0.0.0", , url_path=TOKEN)
    s = bot.Bot(token=TOKEN).set_webhook(
        url=
        "https://dipsupport.herokuapp.com/1143220225:AAFTmo2IBybhLYxKNdHlAL-TYdTJHCe4axw"
    )
    updater.idle()
    #s = bot(token = TOKEN).setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN))
    if s:
        return "webhook setup ok"
    else:
        return "webhook setup failed"
Пример #8
0
def send_image_to_microsoft(id, bot, update):
    global SESSION_ID
    global send_image
    print id
    mybot = bots.Bot(token=apis.telegram_key)
    r = mybot.getFile(id)
    if send_image:
        wordlist = cv.analyzeImages(r['file_path'])
        converted_wordlist = parse(",".join(wordlist), SESSION_ID)
        print converted_wordlist
        bot.sendMessage(
            chat_id=update.message.chat_id,
            text=converted_wordlist['result']['fulfillment']['speech'])
        for x in converted_wordlist['result']['parameters'][
                'location_keywords']:
            collate_voting(x)
def main():
    """Start the bot."""

    notifiers_manager = NotifiersManager(bot.Bot(token))

    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater(token)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(
        CommandHandler("changenotificationperiod", change_notification_period))
    dp.add_handler(CommandHandler("record", print_record))
    dp.add_handler(CommandHandler("average", print_average))
    dp.add_handler(CommandHandler("total", print_total))
    dp.add_handler(CommandHandler("graph", history_graph))
    dp.add_handler(CommandHandler("help", help))
    # for every message
    dp.add_handler(
        MessageHandler(
            (Filters.text | Filters.photo | Filters.video | Filters.document)
            & Filters.group, asd_counter(notifiers_manager=notifiers_manager)))
    # inline messages handler
    updater.dispatcher.add_handler(
        CallbackQueryHandler(button(notifiers_manager=notifiers_manager)))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # all the notifiers are its daemonic processes -> by restarting the manager, every notifier is correctly restarted
    # e.g. monthly -> weekly switch or the asd-bot is added to a new group
    # updater_process = Process(target=updater.idle)
    # global notifiers_manager  # the only way to access it from the asd_counter() and button() functions
    # notifiers_manager = NotifiersManager(bot.Bot(token))
    updater.idle()
Пример #10
0
def cleanChatTimed() -> None:
    global messages

    # Initialize bot
    bot = tb.Bot(TOKEN)

    initialMessageLength = str(len(messages) - len(pinnedMessages))

    # Iterate through messages
    for message in messages:
        if message.message_id not in pinnedMessages:
            try:
                # Delete message, then send to the chat and stdout that the messages
                #   were deleted
                bot.delete_message(chat_id=message.chat_id,
                                   message_id=message.message_id)
            except:
                pass

    print('[RemoBot] ' + initialMessageLength +
          ' messages in the last 24 hours successfully deleted')

    messages = []
Пример #11
0
 def test_bot_init(self, bot_info, monkeypatch):
     if not TEST_NO_PASSPORT:
         monkeypatch.setattr(bot, 'CRYPTO_INSTALLED', False)
     with pytest.raises(RuntimeError, match='passport'):
         bot.Bot(bot_info['token'], private_key=1, private_key_password=2)
Пример #12
0
from telegram import bot
from decouple import config
from flask import Flask, request

TOKEN = config("TOKEN")
bot = bot.Bot(TOKEN)
chat_id = config("CHAT_ID")
app = Flask(__name__)


@app.route(f'/api/{TOKEN}/new_article', methods=["POST"])
def new_article():
    data = request.get_json()
    title = data["post"]["post_title"]
    post = data["post"]["post_content"]
    link = data["post_permalink"]
    text = f"<b>{title}</b>\n{post}\n{link}"
    bot.send_message(chat_id, text, parse_mode="HTML")
    return "1"


@app.route(f'/api/{TOKEN}/new_member', methods=["POST"])
def new_member():
    data = request.get_json()
    name = data["name"]
    text = f"<b>{name}</b> requested to join the campaign"
    bot.send_message(chat_id, text, parse_mode="HTML")
    return "1"
Пример #13
0







==========================
from telegram import update
from telegram import bot
from telegram.ext import Updater

token = '641542217:AAHj-pmdV9Gg9IZ6epNOQDUCiLokDhKZiWs'
updater = Updater(token)
bot = bot.Bot(token)

chat_id = update.Message.chat_id

#print(chat_id)
c = "@cookiesinthefloor"

#bot.polling(none_stop=True, interval=0)

bot.send_message(439943433,"Hello Worlo")

from math import sin, cos, sqrt, atan2, radians

# approximate radius of earth in km
R = 6373000.0
latinput = float(input())
Пример #14
0
import jfw
import models
import pickle
from telegram import bot
from views import Keyboard as k

bot = bot.Bot('587304899:AAFkY8Qv4YQnI4gGwns670STnszZu3CAquI')
u = bot.get_updates()

# u[0].message.reply_text('hello', reply_markup=main_menu_markup)

with open('tests/TeleUser', 'rb') as f:
    tele_user = pickle.load(f)
ru = models.RabonaUser(tele_user)

with open('tests/bot_pickle', 'rb') as f:
    bot = pickle.load(f)
Пример #15
0
def warning(_msg):
    bot.send_message(chat_id=-1001201633175, text=_msg)


# def checkrp(reminder, update):
#     for d in settingtime.keys():
#         if d == time.strftime("%d", time.localtime()):
#             update.message.reply_text("今天要繳" + settingtime[d] + "喔")

if __name__ == "__main__":
    config = configparser.ConfigParser()
    config.read('config.ini')
    # telegram_bot
    telegram_bot_token = config.get('Telegram', 'Access_token')
    bot = tb.Bot(telegram_bot_token)

    # database connection
    # database_url = config.get('Postgresql', 'Database_URL')
    # conn = psycopg2.connect(database_url, sslmode='require')
    # print(conn)
    # cursor = conn.cursor()
    #
    # postgreSQL_select_Query = "select * from bill"
    # cursor.execute(postgreSQL_select_Query)
    # print("Selecting rows from mobile table using cursor.fetchall")
    # mobile_records = cursor.fetchall()
    #
    # print("Print each row and it's columns values")
    # for row in mobile_records:
    #     print("Id = ", row[0])
Пример #16
0
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class NotifiersManager(metaclass=Singleton):
    def __init__(self, bot):
        self.notifiers = []
        self.bot = bot
        self.init_notifiers()

    def init_notifiers(self):
        with open(group_db, 'r') as g_db:
            for group in g_db.readlines():
                chat_id = str(group.split(" ")[0])
                weekly = bool(int(group.split(" ")[1]))
                self.notifiers.append(Process(target=notify, args=(self.bot, weekly, chat_id), daemon=True))
        for notifier in self.notifiers:
            notifier.start()
        for notifier in self.notifiers:
            notifier.join()

    def restart_notifiers(self):
        for notifier in self.notifiers:
            notifier.terminate()
        time.sleep(0.5)
        self.init_notifiers()

notifiers_manager = NotifiersManager(bot.Bot(token))
Пример #17
0
            return rsi

        data = list(klines_close_list)
        period = 14

        y = relative_strength_index(data, period)

        for i in range(0, len(y)):
            if np.isnan(y[i]).any():
                y[i] = 0
        print(y[-1])
        if y[-1] <= float(row["RSI"]) and signal_col[k] == 0:
            signal_col[k] = 1
            BOT_TOKEN = ''
            CHAT_ID = '-213082329'
            tbot = bot.Bot(BOT_TOKEN)
            #signal_col.append(1)
            #tbot.send_message(chat_id=CHAT_ID, text=' '+ row["symbol"] +' '+ row["intervals"].split('_')[-1]+ ' RSI is under ' + str(row["RSI"]) +' ')
            print(' ' + row["symbol"] + ' ' +
                  eval(row["intervals"]).split('-')[0] + ' RSI is under ' +
                  str(row["RSI"]) + ' ')
            #print(row["intervals"].split("_")[-1])
        elif y[-1] > float(row["RSI"]):
            signal_col[k] == 0
        k += 1
        print(k)
        #print(signal_col[0:10])
time.sleep(300)
"""plt.plot(relative_strength_index(data, period))
   plt.ylabel('RSI')
   plt.show()"""