import re from requests import get import urllib.request import urllib.parse import time import datetime from bs4 import BeautifulSoup # 정상적으로 모듈임포트 완료/기본설정 시작 안내 print("\n모듈 임포트 완료!\n기본 설정중. . .") #토큰을 변수에 저장 meal_token = '토큰' #봇 선언 bot = telegram.Bot(token = meal_token) #커스텀 키보드 설정 custom_keyboard = [ ["/help", "공유하기!"], ["Winsub 상태", "Winsub 링크"], ] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) #시간설정 n = time.localtime().tm_wday now = datetime.datetime.now() # 윈섭 xml 리스트 확인 file = open(filename, 'w') xml=file.read()
def send_custom_message(event, context): bot = telegram.Bot(token=os.environ['TELEGRAM_BOSSKU_TOKEN']) bot.sendMessage(chat_id=-423948345, text=event['body']) return {"statusCode": 200, "body": json.dumps(event)}
def __init__(self): super().__init__() self.setupUi(self) self.tr = 0 #총TR요청횟수 #텔레그램봇 my_token = '692301814:AAEfmddhyZPcO0Uzh8r5ZehfooTPOvKOOqc' self.mybot = telegram.Bot(token=my_token) self.chat_id = 544924927 self.kiwoom = Kiwoom() #키움인스턴스 생성 self.kiwoom.comm_connect() #API로그인 self.ts_1_p = 'False' #거래전략1 초기값 self.market_start = 'false' #마켓 초기값 self.market_close = 'false' self.shutdown_0900 = 'false' self.shutdown_1530 = 'false' # Timer1 self.timer = QTimer(self) self.timer.start(1000) #1초 상태바 self.timer.timeout.connect(self.timeout) # Timer2 self.timer2 = QTimer(self) self.timer2.start(1000 * 25) #25초 잔고조회 self.timer2.timeout.connect(self.timeout2) # Timer3 self.timer3 = QTimer(self) self.timer3.start(1000 * 30) #30초 매수전략1 self.timer3.timeout.connect(self.timeout3) # Timer4 self.timer4 = QTimer(self) self.timer4.start(1000 * 33) # 33초 매도전략 self.timer4.timeout.connect(self.timeout4) # Timer5 self.timer5 = QTimer(self) self.timer5.start(1000 * 15) # 60초 09:00~15:30 장중모드 self.timer5.timeout.connect(self.timeout5) # Timer7 self.timer7 = QTimer(self) self.timer7.start(1000 * 1800) # 30분 중간보고, 장마감후 어플 및 컴퓨터 종료 self.timer7.timeout.connect(self.timeout7) self.list700 = [] self.list600 = [] self.buy_list = [] self.sell_list = [] #버튼, 이벤트발생 self.lineEdit.textChanged.connect(self.code_changed) #종목코드 입력시 self.pushButton.clicked.connect(self.send_order) #현금주문 버튼 클릭시 self.pushButton_2.clicked.connect(self.check_balance) #계좌정보 조회 self.pushButton_3.clicked.connect(self.trading_strategy_1) #거래전략1호 self.pushButton_4.clicked.connect(self.quit_app) #앱종료 self.pushButton_4.clicked.connect(QCoreApplication.instance().quit) # 앱종료 self.pushButton_5.clicked.connect(self.timeout7) # 테스트버튼 #계좌정보 accouns_num = int(self.kiwoom.get_login_info("ACCOUNT_CNT")) accounts = self.kiwoom.get_login_info("ACCNO") accounts_list = accounts.split(';')[0:accouns_num] self.comboBox.addItems(accounts_list) #프로그램시작알림 log.info('프로그램이 시작되었습니다.') self.textEdit.append('\n' + QDateTime.currentDateTime().toString("yyyy/MM/dd\nhh:mm:ss") +"ㅣ 프로그램이 시작되었습니다.") self.mybot.sendMessage(self.chat_id, text='\n' + QDateTime.currentDateTime().toString("yyyy/MM/dd\n hh:mm:ss") + "ㅣ 프로그램이 시작되었습니다.") self.get_etf_etn_list() # ETN, ETF 종목 리스트 저장
try: sheet_ongleNotes.insert_row(row, googleNextRow, 'USER_ENTERED') except gspread.exceptions.APIError as argh: print("Maximum d'ajout pour Google sheet - relancer dans 2 min") print("api error : ", argh, file=sys.stderr) inventaireNote = inventaireNote + "\n__api.error.max__" erreurApiMax = True break inventaireNote = inventaireNote + "\n " + uneNoteSite.libelleMatiere.lower() + " " + str(theValeur) + "/" + str(theNoteSur) + " (" + str(theCoef) + ")" if ( uneNoteSite.nonSignificatif == True ): inventaireNote = inventaireNote + "_ns_" googleNextRow = googleNextRow + 1 nbCreate = nbCreate + 1 else: print("Note %s" % uneNoteSite.valeur, " @ déjà présente") print("Nombre de notes ajoutées pour ",elevePrenom," = ", nbCreate) telegram_message = telegram_message + "\n *" + elevePrenom + "* :`" + str(nbCreate) + "`" if ( (nbCreate > 0) or (erreurApiMax) ): telegram_message = telegram_message + inventaireNote break if ( not trouveEleve ): print(">> Eleve config non trouvé !!") print("Fin extraction.\nTotal nouvelles notes=" + str(compteurTotalNouvelleNote)) if ( str(args.telegram) == "yes" ) : bot = telegram.Bot(token=str(args.token)) bot.send_message(chat_id=str(args.chatid), text=telegram_message, parse_mode=telegram.ParseMode.MARKDOWN)
import telegram import requests from telegram import ReplyKeyboardMarkup from telegram.ext import CommandHandler, Filters, MessageHandler, Updater from config import BOT_TOKEN bot = telegram.Bot(token=BOT_TOKEN) updater = Updater(token=BOT_TOKEN, workers=1) dispatcher = updater.dispatcher IPADDR = requests.get("http://ipinfo.io/ip").text.replace("\n", "").replace(" ", "") print("> Your IP Address: {}".format(IPADDR)) def Start(bot, update): update.effective_message.reply_text( "Hello!\nTo get help usage, type /help\n\nBot created by @AyraHikari.\nDonate: paypal.me/AyraHikari\nSource code: https://github.com/AyraHikari/Telegram-git-python", parse_mode="markdown") def Help(bot, update): text = """ *How to use:* -> Copy this URL > `http://{}:5000/{}` -> Go to git, and create a new *Webhooks*, and fill config: Content type: `application/json` """.format(IPADDR, update.effective_message.chat.id) update.effective_message.reply_text(text, parse_mode="markdown")
CallbackQueryHandler(movies_callback_query_handler) ], Series: [ CommandHandler('cancel', cancel), CommandHandler('movies', change_to_movies), MessageHandler(Filters.text, search_series), CallbackQueryHandler(series_callback_query_handler) ] }, fallbacks=[CommandHandler('cancel', cancel)]) dp.add_handler(conv_handler) # log all errors dp.add_error_handler(error) # Start the Bot bot.send_message(chat_id=manager_id, text="Im Up !!") updater.start_polling() # Run the bot until you press Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. updater.idle() if __name__ == '__main__': bot = telegram.Bot(token=telegram_bot_token) imdb = IMDb() main()
camera = cv2.VideoCapture(0) 19 recognizer = cv2.face.LBPHFaceRecognizer_create() recognizer.read('trainer.yml') auth_token = '417489646:AAG0ZJ09qVJhykNOyHrLb9wPdg_iGCYekaM' bot = telegram.Bot(token=auth_token) admin = bot.get_me() channel_id ='@gotnotf' i=0 while True: ret, frame = camera.read() gray_frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY) face = face_classifier.detectMultiScale(gray_frame,1.3,5) ig=BytesIO(frame)
import telegram from decouple import config bot = telegram.Bot(config('TOKEN')) print(bot.get_me())
import threading import telegram from telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, InlineKeyboardMarkup, InlineKeyboardButton, ForceReply from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, CallbackQueryHandler from config import TOKEN, ADMIN_ID, ADMIN_COMMAND_START, ADMIN_COMMAND_QUIT, PAY_TIMEOUT import sqlite3 import time import datetime import random import os from epay import make_data_dict, epay_submit, check_status ROUTE, CATEGORY, PRICE, SUBMIT, TRADE = range(5) ADMIN_ROUTE, ADMIN_CATEGORY_ROUTE, CATEGORY_FUNC_EXEC, ADMIN_GOODS_ROUTE, ADMIN_GOODS_STEP1, ADMIN_GOODS_STEP2, \ ADMIN_CARD_ROUTE, ADMIN_TRADE_ROUTE, ADMIN_CARD_STEP1, ADMIN_CARD_STEP2, ADMIN_TRADE_EXEC = range(11) bot = telegram.Bot(token=TOKEN) def run_bot(): updater = Updater(token=TOKEN, use_context=True) dispatcher = updater.dispatcher admin_handler = ConversationHandler( entry_points=[CommandHandler(ADMIN_COMMAND_START, admin)], states={ ADMIN_ROUTE: [ CallbackQueryHandler(admin_entry_route, pattern='^' + str('分类') + '$'), CallbackQueryHandler(admin_entry_route, pattern='^' + str('商品') + '$'), CallbackQueryHandler(admin_entry_route, pattern='^' + str('卡密') + '$'), CallbackQueryHandler(admin_entry_route, pattern='^' + str('订单') + '$'),
import telegram import pymongo import pprint from pymongo import MongoClient #mongodb client from telegram.ext import CommandHandler from telegram.ext import Updater from telegram.ext import MessageHandler, Filters client = MongoClient() db = client.test_database db = client.test_collection db = client.test_database collection = client.test_collection posts = db.posts #creat new collection named posts #----------------------------------------------------------------------------- bot = telegram.Bot(token='TOKEN') updater = Updater(token='TOKEN') dispatcher = updater.dispatcher #----------------------------------------------------------------------------- def start(bot, update): bot.send_message(chat_id=update.message.chat_id, text="I'm a bot, please talk to me!") #----------------------------------------------------------------------------- start_handler = CommandHandler('start', start) #Link start function to \start command dispatcher.add_handler(start_handler) #add start handler to dispatcher
import weechat import time import telegram bot = telegram.Bot(token='ADD YOUR TOKEN HERE') weechat.register("jackPing", "FlashCode", "1.0", "GPL3", "OH NO", "", "") weechat.prnt("", "Use without jack2 permition is not allowed") def i_am_author_of_message(buffer, nick): """Am I (the current WeeChat user) the author of the message?""" return weechat.buffer_get_string(buffer, 'localvar_nick') == nick def nick_that_sent_message(tags, prefix): for tag in tags: if tag.startswith('nick_'): return tag[5:] if prefix.startswith(('~', '&', '@', '%', '+', '-', ' ')): return prefix[1:] return prefix #process messages def message(data, bufferp, tm, tags, display, is_hilight, prefix, msg): nick = nick_that_sent_message(tags.split(','), prefix) if (is_hilight or weechat.buffer_get_string(bufferp, 'localvar_type') == 'private') and not(i_am_author_of_message(bufferp, nick)): mes = '<' + nick_that_sent_message(tags.split(','), prefix) + '>: ' +msg if weechat.buffer_get_string(bufferp, 'localvar_type') != 'private': mes = weechat.buffer_get_string(bufferp, 'short_name') + ': ' + mes for i in range(0,10): bot.send_message(chat_id=SET CHAT ID, text=mes) return weechat.WEECHAT_RC_OK
def get_bot(): return telegram.Bot(token=settings.TELEGRAM_TOKEN)
import time import configparser import telegram import getapod import numpy as np from apscheduler.schedulers.blocking import BlockingScheduler config = configparser.ConfigParser() config.read('config.ini') bot = telegram.Bot(token=(config['TELEGRAM']['ACCESS_TOKEN'])) url = 'https://apod.nasa.gov/apod/astropix.html' url_zh = 'http://sprite.phys.ncku.edu.tw/astrolab/mirrors/apod/apod.html' def job(): id = np.loadtxt('id.txt') id = np.unique(id) pic = getapod.get_pic(url) exp = getapod.get_exp(url_zh,'zh') bot.send_message(chat_id='@APOD_hans', text = pic) bot.send_message(chat_id='@APOD_hans', text= exp , parse_mode='Markdown') time.sleep(1) for w in id: time.sleep(1) bot.send_message(chat_id=w, text = pic) bot.send_message(chat_id=w, text= exp , parse_mode='Markdown') scheduler = BlockingScheduler()
SOURCE_TOKEN = os.getenv('SOURCE_TOKEN', "") HOST = os.getenv('HOST') # Same FQDN used when generating SSL Cert PORT = int(os.getenv('PORT', 8443)) CERT = os.getenv('CERT') CERT_KEY = os.getenv('CERT_KEY') DISABLE_SSL = os.getenv('DISABLE_SSL') PERMANENT_CHATS = os.getenv( 'PERMANENT_CHATS') # Comma separated ids wrapped in a string OWNER_ID = os.getenv('OWNER_ID') DEBUG = int(os.getenv('DEBUG', 0)) DEBUG_STATE = {0: logging.ERROR, 1: logging.DEBUG} ADMIN_LEVEL = 1 # 1=Channel admins + Owner, 2=Channel admins, 3=Owner only telegram_bot = telegram.Bot(TOKEN) app = Flask(__name__) @app.route('/healthz') def healthz(): return "OK" @app.route('/relay/' + SOURCE_TOKEN, methods=['POST']) def relay(): with app.app_context(): muted = current_app.muted chats = current_app.chats if not muted:
def activate(self, channel): config = channel.config_json() bot = telegram.Bot(config['auth_token']) bot.set_webhook("https://" + channel.callback_domain + reverse('courier.tg', args=[channel.uuid]))
from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive import telegram from telegram.ext import Updater from telegram.ext import CommandHandler import random import os import time import schedule import threading import settings bot = telegram.Bot(token=settings.BOT_TOKEN) updater = Updater(token=settings.BOT_TOKEN, use_context=True) dispatcher = updater.dispatcher def start(update, context): context.bot.send_message( chat_id=update.effective_chat.id, text= "Hello, I'm bot for sending memes\n add me as an admin to channel and add it's name to settings" ) start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler) updater.start_polling()
def deactivate(self, channel): config = channel.config_json() bot = telegram.Bot(config['auth_token']) bot.delete_webhook()
def get_client(): if not settings.TELEGRAM_NOTIFICATIONS: return None return telegram.Bot(token=settings.TELEGRAM_TOKEN)
load_dotenv() logging.basicConfig( level=logging.DEBUG, filename='main.log', filemode='w', format='%(asctime)s, %(levelname)s, %(name)s, %(message)s', ) PRAKTIKUM_TOKEN = os.getenv('PRAKTIKUM_TOKEN') TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN') CHAT_ID = os.getenv('TELEGRAM_CHAT_ID') API_URL = 'https://praktikum.yandex.ru/api/user_api/' bot = telegram.Bot(token=TELEGRAM_TOKEN) def parse_homework_status(homework): """Парсинг статуса домашней работы""" homework_name = homework.get('homework_name') homework_status = homework.get('status') if homework_name is None or homework_status is None: message = 'Не удалось получить данные.' logging.error(message) return message if homework_status == 'rejected': verdict = 'К сожалению в работе нашлись ошибки.' elif homework_status == 'approved':
cursor = conn.cursor() cursor.execute("select * from users") for row in cursor: user = row['user'] if user in CONFIG: prev_mapping = CONFIG[user] for key in row.keys(): prev_mapping[key] = row[key] CONFIG[user] = prev_mapping token = cursor.execute("select token from bots where bot_name='eragon'").fetchone()['token'] print(CONFIG) bot = telegram.Bot(token=token, request=Request(con_pool_size=4, connect_timeout=30,read_timeout=30)) # updater = Updater(token=token) driver = webdriver.Chrome() driver.implicitly_wait(30) driver.get("https://www.binance.com/trade.html") wait = WebDriverWait(driver, 120) element = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, 'main-aside'))) print('Starting to monitor') i = 0 while True: summary_iteration = (i%SUMMARY_CYCLE)==0
import requests import random import telegram import json from django.shortcuts import render,redirect from decouple import config from restaurant.models import Restaurant from accounts.models import Telegram from django.views.decorators.http import require_POST from django.http import JsonResponse from django.db.models import Q api_url = 'https://api.telegram.org' token = config('TELEGRAM_BOT_TOKEN') #프로젝트내에 .env에서 정보를 가져옴 chat_id = config('CHAT_ID') bot = telegram.Bot(token=token) def index(request): return render(request, 'chatbot/index.html' ) def telegram_chat_schedule(request): #telegram chat_id 등록된 모든 사용자에게 추천 메시지 발송 status=1 error_msg='' try : telegram_users = Telegram.objects.all() print('>>>>>>>>>>>>>') print(telegram_users) restaurants = Restaurant.objects.filter(r_type='한식') sel_obj = random.choice(restaurants)
def send(msg, chat_id, token=telegram_token): bot = telegram.Bot(token=telegram_token) bot.sendMessage(chat_id=chat_id, text=msg, parse_mode='HTML')
#!/usr/bin/python3 import json import base64 import hashlib import requests import telegram with open("config.json", "r") as fd: config = json.load(fd) with open("websites.json", "r") as fd: websites = json.load(fd) bot = telegram.Bot(config["telegram-token"]) changed = False for site in websites: try: response = requests.get(site["url"]) response.raise_for_status() content = response.text.encode("utf-8") except: continue digest = hashlib.sha512(content).digest() digest = base64.b64encode(digest).decode("ascii") if site["hash"] != digest: site["hash"] = digest changed = True
from telegram import ParseMode import numpy as np from trading_client import TradingClient from binance.client import Client from datetime import datetime from collections import deque trade_currency = sys.argv[1] base_currency = sys.argv[2] frame = int(sys.argv[3]) history_window = int(sys.argv[4]) binance_key = 'lRAn2l36Qfvv9e9yDlIDWK9dpEfKRKrVbbBO8ynHcHd5eA0voNBbGBcrW4n3zlZ5' binance_secret = 'bwd309D5pzgUioC9rxlJKpvAg5qwFU9zIkCLop9knRVki8nu3i3Ba88Z7K9xzV6p' client = TradingClient(base_currency, trade_currency, binance_key, binance_secret) telegram_bot = telegram.Bot( token='599534060:AAFPzCZkojZNje8rjapHRZdYm-EaLsT-EH4') close_prices = deque(maxlen=history_window) def updated_statistics(): start_ts = (int(datetime.now().strftime('%s')) - history_window * 60) * 1000 klines = client.get_historical_klines(Client.KLINE_INTERVAL_3MINUTE, start_ts) prices = np.array([float(kline[4]) for kline in klines]) return prices def report(): Timer(int(frame * 60), report).start() prices = updated_statistics()
def send_message(event, context): bot = telegram.Bot(token=TOKEN) bot.sendMessage(chat_id=CHAT_ID, text='Hello World!') return { "statusCode": 200, }
import telegram import csv import traceback import datetime import re import time import src.botCommands as Commands from src import globalVars APIKEY = "" with open('apikey.csv', 'r+') as csvfile: # Read in the API key from the .csv file reader = csv.DictReader(csvfile) APIKEY = list(reader)[0]['key'] cahm = telegram.Bot(token=APIKEY) # Make the bot object updates = list() # A list for updates from the teleram chat currMess = list() # A list to hold the current message we're looking at globalVars.init() # Bring in the global variables print("Cards Against Huge Manatees Bot 1.0") print("Team Synergy") newestOffset = 0 networkFailure = False while not networkFailure: # Get the initial batch of chat messages try: updates = cahm.getUpdates(offset=newestOffset, timeout=3,
def check_connection(): bot = telegram.Bot(token=os.environ.get("BOT_TOKEN")) print(bot.get_me())
"dbName": "razer_hackathon", "dbType": "mysql" } usrname = credentials["username"] pwd = credentials["password"] string = credentials["dbString"] port = credentials["port"] dbname = credentials["dbName"] dbtype = credentials["dbType"] engine = sa.create_engine( f"{dbtype}://{usrname}:{pwd}@{string}:{port}/{dbname}") conn = engine.connect() bot = telegram.Bot(token='1263177008:AAHeKwgn6QYd44qUwMylQLvvWF7nAdmuQeE') totp = pyotp.TOTP("JBSWY3PCBHPK3PXP") @app.route("/login", methods=['POST']) def login(): username = request.json['data'][0] password = request.json['data'][1] if (username == 'kevinou' and password == 'kevinou'): success = 'True' token = str(uuid.uuid4()) output = [success, token] msg = totp.now() chat_id = bot.get_updates()[-1].message.chat_id bot.send_message(chat_id=chat_id, text=msg) else:
import sys from io import BytesIO import telegram from flask import Flask, request, send_file from fsm import TocMachine API_TOKEN = '395423824:AAF2QzgURYrTUBGUnLDrSs7eSQLobyRaHx0' WEBHOOK_URL = 'https://80b22c68.ngrok.io/hook' app = Flask(__name__) bot = telegram.Bot(token=API_TOKEN) machine = TocMachine( states=[ 'user', 'start', 'state1', 'state2', 'state3', 'state4', 'state5', 'state6', 'state7', 'state8', 'state9', 'state10', 'state11', 'state12', 'state13',
def onLoad(self): """!Called by import of the plugin""" self.bot = telegram.Bot(token=self.config.get("botToken", default=""))