I have the basic code for sending a photo and i seem to understand the concept of choosing a random one. My question is where in this code should i put the random choice code?
import sys
import time
import os
import telepot
from telepot.loop import MessageLoop
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
import random
def on_chat_message(msg):
global chat_id
content_type, chat_type, chat_id = telepot.glance(msg)
#creating buttons
if content_type == 'text':
if msg['text'] == '/start':
bot.sendMessage(chat_id, 'Welcome to randomImgBot\nOn each click i will display you a random image of your choice\n Created by JonSnow 2021',reply_markup = InlineKeyboardMarkup(inline_keyboard=[
[InlineKeyboardButton(text="PGP",callback_data='a')]]))
def on_callback_query(msg):
global chat_id
query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
print('Callback Query:', query_id, from_id, query_data)
if query_data == 'a':
bot.sendPhoto(chat_id, photo=open('lolly.png'))
bot = telepot.Bot('')
MessageLoop(bot, {'chat': on_chat_message,
'callback_query': on_callback_query}).run_as_thread()
print('Listening ...')
while 1:
time.sleep(10)
Related
i am searching for a solution. I hava a bot which post by /start command some stuff i need. But id like that the bot do this in a defined time, maybe every 6h.
Hope someone could help me.
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from tracker import get_prices
telegram_bot_token = "xxx-xxx"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
chat_id = update.effective_chat.id
message = ""
crypto_data = get_prices()
for i in crypto_data:
coin = crypto_data[i]["coin"]
price = crypto_data[i]["price"]
change_day = crypto_data[i]["change_day"]
change_hour = crypto_data[i]["change_hour"]
message += f"Coin: {coin}\nPrice: ${price:,.2f}\nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
context.bot.send_message(chat_id=chat_id, text=message)
dispatcher.add_handler(CommandHandler("start", start))
updater.start_polling()
I was testing something an could add an timer, but is there a way to loop the programm with while True: ?
import telegram
from telegram.ext import Updater
from telegram.ext import CommandHandler
from tracker import get_prices
import threading
import time
telegram_bot_token = "xxx:xxx"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def message_timer(update, context):
time.sleep(10)
chat_id = update.effective_chat.id
message = ""
crypto_data = get_prices()
for i in crypto_data:
coin = crypto_data[i]["coin"]
price = crypto_data[i]["price"]
change_day = crypto_data[i]["change_day"]
change_hour = crypto_data[i]["change_hour"]
message += f"Coin: {coin}\nPrice: ${price:,.2f}\nHour Change: {change_hour:.3f}%\nDay Change: {change_day:.3f}%\n\n"
context.bot.send_message(chat_id=chat_id, text=message)
dispatcher.add_handler(CommandHandler("start", message_timer))
updater.start_polling()
I have some code:
master = InlineKeyboardMarkup()
master.add(InlineKeyboardButton(text='7(800)555-35-35', url='tel:+78005553535'),
InlineKeyboardButton(text='8(800)555-35-35', url='tel:+88005553535'))
But when I try to summon this keyboard I have an error:
aiogram.utils.exceptions.BadRequest: Wrong http url
You need to write the code as follows:
main.py
from aiogram
import Bot, Dispatcher, executor, types
import keyboards as kb
bot = Bot(token = 'BOT_TOKEN')
dp = Dispatcher(bot)
#dp.message_handler(commands = ['inline'])
async def show_items(message: types.Message):
await message.answer('It is buttons', reply_markup = kb.start_keyboard)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates = True)
keybords.py
from aiogram.types
import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
inline_keyboard = InlineKeyboardButton(text='7(800)555-35-35', url = 'tel:+78005553535'),
InlineKeyboardButton(text='8(800)555-35-35', url = 'tel:+88005553535')
start_keyboard = ReplyKeyboardMarkup(resize_keyboard = True).add(inline_keyboard)
Hi I'm trying to leave a channel with id with this script but it not showing any results well LeaveChannelRequest doesn't worked for me too
here is what i tried:
import asyncio
import logging
import re
import time
import os
import sys
import requests
logging.basicConfig(level=logging.ERROR)
from telethon import TelegramClient, events
from telethon.tl.functions.channels import LeaveChannelRequest
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.tl.functions.messages import GetBotCallbackAnswerRequest
from datetime import datetime
from colorama import Fore, init as color_ama
color_ama(autoreset=True)
os.system('cls' if os.name=='nt' else 'clear')
# my.telegram.org values, get your own there
api_id = ''
api_hash = ''
input_channel = '-1001226909513'
def print_msg_time(message):
print('[' + Fore.YELLOW + f'{datetime.now().strftime("%H:%M:%S")}' + Fore.RESET + f'] {message}')
async def main():
if len(sys.argv) < 2:
print('Usage: python start.py phone_number')
print('-> Input number in international format (example: +10123456789)\n')
e = input('Press any key to exit...')
exit(1)
phone_number = sys.argv[1]
if not os.path.exists("session"):
os.mkdir("session")
client = TelegramClient('session/' + phone_number, api_id, api_hash)
await client.start(phone_number)
me = await client.get_me()
print(Fore.GREEN + f' Current account: {me.first_name}({me.username})\n' + Fore.RESET)
print_msg_time('leaving channels')
async def main():
await client.delete_dialog(input_channel)
print_msg_time(f'{input_channel} has been leaved')
asyncio.get_event_loop().run_until_complete(main())
where is my problem?
The method call to leave the channel or group is defined in inner function
[...]
print_msg_time('leaving channels')
async def main():
await client.delete_dialog(input_channel)
print_msg_time(f'{input_channel} has been leaved')
which isn't called in outer function, you could avoid using a inner function. for example, you can call delete_dialog method like this
[...]
print_msg_time('leaving channels')
await client.delete_dialog(input_channel)
print_msg_time(f'{input_channel} has been leaved')
I need help with this code.
A month ago, I modified it to fit with me.
since three days, I suffer from an error that I could not fix .. He used to work before and now no
Thank you so much.
This is the source of the project
I have just modified the previous mistakes
I'm a beginner with only a month and a half experience
https://github.com/P-Alban/Telegram-collector
import sys
from getpass import getpass
from time import sleep
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.errors import UsernameNotOccupiedError
from telethon.errors import FloodWaitError
from telethon.tl.functions.channels import GetParticipantsRequest
from telethon.tl.functions.contacts import ResolveUsernameRequest
from telethon.tl.types import ChannelParticipantsSearch, InputChannel
# First you need create app on https://my.telegram.org
api_id = api_id
api_hash = 'api_hash'
phone = '+....Phone'
limit = 100
def get_chat_info(username, client):
try:
chat = client(ResolveUsernameRequest(username))
except UsernameNotOccupiedError:
print('Chat/channel not found!')
sys.exit()
result = {
'chat_id': chat.peer.channel_id,
'access_hash': chat.chats[0].access_hash
}
return result
def dump_users(chat, client):
counter = 0
offset = 0
chat_object = InputChannel(chat['chat_id'], chat['access_hash'])
all_participants = []
print('Process...')
while True:
participants = client.invoke(GetParticipantsRequest(
chat_object, ChannelParticipantsSearch(''), offset, limit
))
if not participants.users:
break
all_participants.extend(['{} {}'.format(x.id, x.username)
for x in participants.users])
users_count = len(participants.users)
offset += users_count
counter += users_count
print('{} users collected'.format(counter))
sleep(2)
with open('users.txt', 'w') as file:
file.write('\n'.join(map(str, all_participants)))
def main():
channel_name = input('Input a channel name, without "#": ')
client = TelegramClient(phone, api_id, api_hash)
print('Connecting...')
client.connect()
if not client.is_user_authorized():
try:
client.send_code_request(phone)
print('Sending a code...')
client.sign_in(phone, code=input('Enter code: '))
print('Successfully!')
except FloodWaitError as FloodError:
print('Flood wait: {}.'.format(FloodError))
sys.exit()
except SessionPasswordNeededError:
client.sign_in(password=getpass('Enter password: '))
print('Successfully!')
dump_users(get_chat_info(channel_name, client), client)
print('Done!')
if __name__ == '__main__':
main()
I made a telegram bot which sends photo upon request from URL using pyTelegramBotAPI wrapper. So I tried putting a dummy photo URL and test if the bot can send the image but it failed with the following error.
telebot.apihelper.ApiException: sendPhoto failed. Returned result: <Response [400]>
I'm not sure what the error is, but how can I send a photo from URL using Telegram Bot API correctly? Here is my code
import telebot
import time
import urllib
from io import BytesIO
from PIL import Image
TOKEN = '<token here>'
url='http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg'
def listener(*messages):
for m in messages:
chatid = m.chat.id
if m.content_type == 'text':
text = m.text
name = m.fromUser.first_name
msgid = m.message_id
if(text.startswith('/photo')):
img = BytesIO(urllib.request.urlopen(url).read())
tb.send_chat_action(chatid, 'upload_photo')
tb.send_photo(chatid, img, reply_to_message_id=msgid)
tb = telebot.TeleBot(TOKEN)
tb.get_update() # cache exist message
tb.set_update_listener(listener) #register listener
tb.polling()
while True:
time.sleep(1)
I'm not sure whether I missed something though.
Try this:
import telebot
import time
import urllib
url = 'http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg'
f = open('out.jpg','wb')
f.write(urllib.request.urlopen(url).read())
f.close()
def listener(*messages):
for m in messages:
chat_id = m.chat.id
if m.content_type == 'text':
text = m.text
msgid = m.message_id
if text.startswith('/photo'):
tb.send_chat_action(chat_id, 'upload_photo')
img = open('out.jpg', 'rb')
tb.send_photo(chat_id, img, reply_to_message_id=msgid)
img.close()
tb = telebot.TeleBot(TOKEN)
tb.set_update_listener(listener) #register listener
tb.polling()
while True:
time.sleep(0)
or (using pyTelegramBotAPI 0.2.0)
import telebot
import time
import urllib
url='http://scontent-b.cdninstagram.com/hphotos-xfa1/t51.2885-15/e15/10919672_584633251672188_179950734_n.jpg'
f = open('out.jpg','wb')
f.write(urllib.request.urlopen(url).read())
f.close()
tb = telebot.TeleBot(TOKEN)
#tb.message_handler(commands=['photo'])
def send_photo(message):
tb.send_chat_action(message.chat.id, 'upload_photo')
img = open('out.jpg', 'rb')
tb.send_photo(message.chat.id, img, reply_to_message_id=message.message_id)
img.close()
tb.polling()
while True:
time.sleep(0)
elif 'Hi' in text:
reply(img=urllib2.urlopen('img url').read())