Good evening, I am developing a bot that will search for a telegram account by phone number. Tell me what I'm doing wrong: KeyError 'result' crashes.
user = response['result']
# Импортируем модули
import telebot
import requests
# Указываем токен
bot = telebot.TeleBot('')
# Обработчик команды Start
#bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, 'Введите номер телефона для поиска аккаунта телеграмм')
# Обработчик ввода номера телефона
#bot.message_handler(content_types=['text'])
def send_text(message):
# Запрос для поиска пользователя
url = 'https://api.telegram.org/bot{bot}/getUserByPhone' + 'phone_number=' + message.text
response = requests.get(url).json()
# Проверка существования пользователя
if 'message' in response:
bot.send_message(message.chat.id, 'Аккаунт телеграмм не найден')
else:
user = response['result']
bot.send_message(message.chat.id, 'Указанный аккаунт был найден:\n\n' +
'ID пользователя: ' + str(user['id']) + '\n\n' +
'Имя пользователя: ' + user['first_name'])
# Запуск бота
bot.polling()
I tried to deal with the error myself, but since I'm not strong in python, it didn't work out for me
Related
I am writing a telegram bot based on OpenAI. There is a problem with multithreading. When one user asks the bot, another person can get the same information.
For example:
First user: Do you know Konstantin Polukhin?
Bot: Yes, and begins to describe it..
The second user: Do you respect him?
Bot: Yes, I know Konstantin Polukhin.
It is necessary to make sure that the data does not overlap and the bot can say something related to the request of another user.
I tried many methods that were suggested, but none helped.
Code:
from aiogram import Bot,types
import openai
import requests
from googletrans import Translator
from aiogram.utils import executor
from aiogram.dispatcher import Dispatcher
TOKEN = " "
bot = Bot(token=TOKEN)
openai.api_key = " "
dp = Dispatcher(bot)
my_list = [" ", " ", ""]
#dp.message_handler(content_types = ["text"])
async def start(message: types.Message):
#print("\n" + my_list[0] + "\n" + my_list[1])
translator = Translator()
dest_language = "en"
translated_text = translator.translate(message.text, dest=dest_language).text
my_list[2] = "\n\nHuman: " + translated_text + "\n\nAI: "
response = openai.Completion.create(
model="text-davinci-003",
prompt=f"{my_list[0] + my_list[1] + my_list[2]}",
temperature=0.5,
max_tokens=1024,
top_p=1.0,
frequency_penalty=0.5,
presence_penalty=0.0)
dest_language_2 = "ru"
translated_text1= translator.translate(text=response['choices'][0]['text'], dest=dest_language_2).text
await message.answer(translated_text1)
my_list[1] = "\n\nAI: " + response.choices[0].text
my_list[0] = "\n\nHuman: " + translated_text
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=False)```
At the moment, I was implementing a system using telethon and telebot, you yourself understand - an error occurs with thread, this option does not suit me, is there any other way to check an account by phone number? Or what can replace telethon? I tried in pyrogram - I could not figure it out. I would be grateful if you send the code / tell me what can be used.
Here is the implementation of my code
#Telegram Bot Library
import telebot
from telebot import types
import random
import requests as req
from bs4 import BeautifulSoup
#Telegram Library
from telethon.sync import TelegramClient
from telethon.tl.functions.contacts import ImportContactsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser, InputPhoneContact
import configparser
cpass = configparser.RawConfigParser()
cpass.read('config.data')
try:
api_id = cpass['cred']['id']
api_hash = cpass['cred']['hash']
phone = cpass['cred']['phone']
client = TelegramClient(phone, api_id, api_hash)
except KeyError:
print("[!] для начала заполните все поля в config.data")
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input('[+] введите код от телеграмм : '))
token = ""
bot = telebot.TeleBot(token)
user_data= {
'number': ''
}
#bot.message_handler(commands=['start', 'go'])
def start_handler(message):
msg = bot.send_message(message.chat.id, 'Здравствуйте! Я создан специально для sexcall.su.\nНапишите номер телефона пользователя :')
bot.register_next_step_handler(msg, user_number)
def user_number(message):
user_data['number'] = message.text
msg = bot.send_message(message.chat.id, 'Отлично, происходит проверка аккаунта, требуется ввести капчу:')
bot.register_next_step_handler(msg, getresults)
def getresults(message):
#Checking the received number via telethon
contact = InputPhoneContact(client_id=0, phone={user_data['number']}, first_name="custom_first_name", last_name="custom_last_name")
result = client(ImportContactsRequest([contact]))
#if the account is not found - display a message
if not client.get_entity({user_data['number']}):
bot.send_message(message.chat.id,"К сожалению, у данного пользователя нет телеграмма, пожалуйста, введите номер телефона : ")
#bot.register_next_step_handler(msg, number)
#If the account is found, execute the following code
else:
url = 'http://******/ocean/oceansite_balance.php?to=%s' % ({user_data['phone']})
resp = req.get(url)
soup = BeautifulSoup(resp.text, 'lxml')
if int(soup.p.string.strip()) == 0:
bot.send_message(message.chat.id,"К сожалению, у данного пользователя не достаточно средств, пожалуйста, введите номер телефона : ")
#bot.register_next_step_handler(msg, number)
bot.infinity_polling()
I write telegram bot with aiogram
There's the function:
async def create_bill(message:types.Message, state: FSMContext):
if message.text.isdigit():
amount = int(message.text)
await message.answer('Создаю счет для оплаты...')
logging.logger_info.info('Создается счет')
bill = p2p.bill(bill_id=message.from_user.id+1, amount=amount, lifetime=5)
payment_url = p2p.check(bill_id=message.from_user.id+1).pay_url
pkb_btn_1 = InlineKeyboardButton('Оплатить', url=payment_url)
pkb_btn_2 = (InlineKeyboardButton(text="Зачислить на счет", callback_data='update_balance'))
pkb_mark_1 = InlineKeyboardMarkup.add(pkb_btn_1)
pkb_full = InlineKeyboardMarkup(row_width=2).add(pkb_btn_1)
pkb_full.add(pkb_btn_2)
logging.logger_info.info(f'Создан счет #{bill.bill_id} на сумму {amount} для пользователя {message.from_user.id}')
await message.answer('Счет создан!\nНажмите на кнопку, чтобы оплатить', reply_markup=pkb_full)
await UserStates.next()
else:
await message.answer('Пожалуйста, введите число!')
logging.logger_info.info(f'Пользователь {message.from_user.id} ввел некорректные данные')
It works and awaiting the inline keyboard with 2 buttons. First button is just a link (it works), second button should to call this handler:
#dp.callback_query_handler(lambda c: c.data == 'update_balance')
async def process_callback_balance_update(callback_query: types.CallbackQuery, state='*'):
if user.get_user_block_status(callback_query.from_user.id):
await callback_query.message.answer('Вы были заблокированы')
logging.logger_warn.warning(f'Заблокированный пользователь {callback_query.from_user.id} пытался подключиться к боту!')
else:
if p2p.check(bill_id=callback_query.from_user.id+1).status != 'PAID':
await callback_query.message.answer('Оплата не прошла!')
logging.logger_warn.warning(f'Пользователь {callback_query.from_user.id} пытался пополнить баланс с неоплаченным счетом!')
else:
current_balance = user.get_user_balance(callback_query.from_user.id)
new_balance = current_balance + p2p.check(bill_id=callback_query.from_user.id+1).amount
logging.logger_info.info(f'Производится зачисление средств на баланс пользователя {callback_query.from_user.id}')
await user.change_user_balance(callback_query.from_user.id, new_balance)
await callback_query.message.answer('Деньги зачислены')
await state.finish()
logging.logger_info.info(f'Деньги зачислены. Баланс пользователя {new_balance}')
await callback_query.answer()
But it's doesn't call handler!
I tried to add/remove state, replace this handler in another place in code, but nothing!
In logs I see this:
aiogram.contrib.middlewares.logging - INFO - Unhandled callback query [ID:1342058245786784398] from user [ID:312472285] for message [ID:621] in chat [private:312472285] with data: users originally posted by user [ID:5621517130]
I read almost all in google, read the docs and examples, tried different ways, but is still doesn't work
Also I have another handler wrote definitely same way and in works correctly
So I made this discord bot and hosted it on Heroku. It fetches the latest tweet from a Twitter account and displays it in a specific channel on discord. It works fine most of the time but sometimes it happens that after a few hours, it fetches and displays the first tweet of the Twitter account again, even though there's no new tweet. I used asyncio.gather() to tackle this problem and it worked fine but it happened again today. I have been trying to solve this problem but to no avail. What do I do?
async def send_to_alert(embed):
await client.get_channel(alert_channel_id).send(content="#everyone", embed=embed)
return
async def send_to_all(embed):
await client.get_channel(all_channel_id).send(content="#everyone", embed=embed)
return
async def send_to_one(text):
await client.get_channel(all_channel_id).send(content=f"#everyone\n{text}")
return
#client.event
async def on_ready():
print('Logged in as ' + client.user.name)
print("Starting to fetch the last tweet from the " + USER_TO_SNITCH + " account")
last_tweet = '0'
while True:
current_last_tweet = \
api.user_timeline(screen_name=USER_TO_SNITCH, count=1, include_rts=False, tweet_mode='extended')[0]
if (int(current_last_tweet.id_str) > int(last_tweet)) and (
not current_last_tweet.full_text.startswith('RT')):
last_tweet = current_last_tweet.id_str
text = current_last_tweet.full_text
if "#chart" not in text and "#CHART" not in text and "#Chart" not in text:
if "#alert" in text or "#Alert" in text or "#ALERT" in text:
embed = alert_found(text)
# await send_to_alert(embed)
# await send_to_all(embed)
await asyncio.gather(send_to_alert(embed), send_to_all(embed))
else:
await asyncio.gather(send_to_one(current_last_tweet.full_text))
else:
media_link = current_last_tweet.extended_entities["media"][0]["media_url_https"]
text = current_last_tweet.full_text.split()
text.pop()
text = " ".join(text)
text = text.replace("#Charts", "").strip()
text = text.replace("#CHARTS", "").strip()
text = text.replace("#charts", "").strip()
text = text.replace("#chart", "").strip()
text = text.replace("#Chart", "").strip()
text = text.replace("#CHART", "").strip()
if text == "":
text = " "
media_embed = discord.Embed(color=0xffd500, description=f"**{text}**").set_image(url=media_link)
await asyncio.gather(client.get_channel(charts_channel_id).send(content="#everyone", embed=media_embed))
time.sleep(10)
client.run(DISCORD_BOT_TOKEN)
I want to setup a telegram bot for receiving multiple images in one message. My bot can receive only the first image, all others are ignored. Here is my code:
# -*- coding: utf-8 -*-
import config
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, InputMediaPhoto
bot = telebot.TeleBot(config.token)
main_menu_keyboard = telebot.types.ReplyKeyboardMarkup(True,True)
main_menu_keyboard.add('test1', 'test2')
welcome_message='''Hello,
dude
'''
dict = {}
class nameDict:
def __init__(self, name):
self.name = name
self.media = None
def process_name_step(message):
try:
chat_id = message.chat.id
name = message.text
upload = nameDict(name)
dict[chat_id] = upload
message = bot.send_message(chat_id, 'Upload your photos: ')
bot.register_next_step_handler(message, process_media_step)
except Exception as e:
bot.reply_to(message, 'Error...')
def process_media_step(message):
try:
chat_id = message.chat.id
media = message.photo[-1].file_id
upload = dict[chat_id]
upload.media = media
bot.send_photo(chat_id, str(upload.media))
except Exception as e:
bot.reply_to(message, 'Error...')
bot.register_next_step_handler(message, process_media_step)
bot.enable_save_next_step_handlers(delay=2)
bot.load_next_step_handlers()
#bot.message_handler(commands=['start'])
def start_message(message):
bot.send_message(message.chat.id, welcome_message, reply_markup=main_menu_keyboard)
#bot.message_handler(content_types=['text'])
def send_text(message):
if message.text.lower() == 'test1':
message = bot.send_message(message.chat.id, 'Enter youe name: ')
bot.register_next_step_handler(message, process_name_step)
elif message.text.lower() == 'test2':
bot.send_message(message.chat.id, 'Empty')
bot.polling()
Could you please me find a solution on how to receive multiple images in a single message to the bot?
Thanks!
I found a workaround just add a photo handler that saves them locally.
#bot.message_handler(content_types=['photo'])
def get_photo(message):
fileID = message.photo[-1].file_id
file_info = bot.get_file(fileID)
downloaded_file = bot.download_file(file_info.file_path)
user_path=str(message.from_user.id)
if not os.path.exists(user_path):
os.makedirs(user_path)
with open(str(message.from_user.id) + '/' + fileID, 'wb') as new_file:
new_file.write(downloaded_file)