I am writing a bot that will give out various media by certain tags. the user writes a request, it is processed and everything found in the database is converted into a list of links of these media, which will then be sent to the user. For example, the script found 100 media satisfying the search query.
how to issue messages in a loop of n messages (for example, n = 10), and to continue issuing, you need to press the inline button? I thought to use AsyncIOScheduler, but as far as I understand, it outputs a cycle over a time interval, but I need exactly the trigger of pressing the button
what do I need to use for this? any scheduler or other handlers?
I was asked to insert a bot initialization block, I don't understand why, if it's standard for any python telegram bot, but okay, here it is
#import block
import asyncio
import string
from asyncio.log import logger
import json
from aiogram.bot.api import TelegramAPIServer
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import logging
import sqlite3
from aiogram.utils.callback_data import CallbackData
from aiogram import Bot, Dispatcher, executor, types
from aiogram.bot import bot
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.utils.markdown import hlink
import config
from utils import States
# Init block
logging.basicConfig(level=logging.INFO)
bot = Bot(token=config.API_TOKEN)
dp = Dispatcher(bot, storage=MemoryStorage())
dp.middleware.setup(LoggingMiddleware())
cb = CallbackData('id', 'action')
for example, my unfinished code
#dp.message_handler(state=States.S_SEND)
async def senn_media(link_list, message: types.Message):
chat_id = message.chat.id
for length in range(10):
caption1 = ("some text")
media1 = link_list[array]
await bot.send_video(chat_id, media1, caption=caption1, parse_mode="HTML")
Related
When writing a bot, I used Inline - keyboard. I found that it was when EXIT (just in the background from the application) and LOGIN (into the application) in Telegram that the response to the button works again, as if it loops. Why is this happening? It seems like it didn't happen before.Is it possible to count on the incorrectness of the Internet or something like that?
It is interesting that anything can be in the body of the function, the code loops in any case...
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
bot = telebot.TeleBot(config.TOKEN)
markup = InlineKeyboardMarkup()
markup.row_width = 1
markup.add(InlineKeyboardButton("My Links", callback_data="my_links"))
#bot.callback_query_handler(func=lambda call: call.data == 'my_links')
def myLinks(call):
# ...
# looping code
# ...
bot.polling()
It might be worth trying to replace the lambda function. To be honest, there are no thoughts
So I am making a trading bot the user first have to type "/BUY" for the first command.
And every user have some settings saved up in files so I want them to choose to buy with old settings or new ones.
I tried to put a command instead of a text but that was impractical because anyone can use it without having to go the first one
This is my code for now:
from telebot import types
import telebot
from decouple import config
BOT_TOKEN = config('BOT_TOKEN')
bot = telebot.TeleBot(BOT_TOKEN)
#bot.message_handler(commands=['Start'])
def msg_hndl(message):
print(message)
markup =types.ReplyKeyboardMarkup(one_time_keyboard=True,selective=True)
markup.row_width = 2
button1 =types.InlineKeyboardButton(text="/BUY",callback_data="test",selective=True)
markup.add(button1)
bot.send_message(message.chat.id,"Choose #"+message.from_user.username, reply_markup=markup)
#bot.message_handler(commands=['BUY'])
def msg_hndl(message):
markup2 = types.ReplyKeyboardMarkup(one_time_keyboard=True,selective=True)
markup2.row_width = 2
button1 = types.InlineKeyboardButton(text="/New_settings", callback_data="test")
button2 = types.InlineKeyboardButton(text="/Old_settings", callback_data="test")
markup2.add(button1,button2)
bot.send_message(message.chat.id,"Choose #"+message.from_user.username, reply_markup=markup2)
#bot.message_handler(commands=['New_settings'])
def msg_hndl(message):
#do something
bot.polling()
So I did the research myself and saw the only solution is to save messages and have a message handler that saves the user id and compare it everytime.
first of all, im a beginner.
Want i want to accomplish is that music plays while the script is executing.
What it does right now it plays the music, waits until the music is over and then executes the rest of the code. That is not what i want. Here my Code:
import os
import subprocess
import multiprocessing
import threading
from playsound import playsound
CurrentPath = os.path.dirname(os.path.normpath(__file__))
os.chdir(CurrentPath)
def music():
Music = "Music.mp4"
#subprocess.run(["ffplay", "-nodisp", "-autoexit", "-hide_banner", Music])
playsound("Music.mp4")
def other_things():
print("Hello World")
#musicp = multiprocessing.Process(target=music())
#restp = multiprocessing.Process(target=other_things())
musicp = threading.Thread(target=music())
restp = threading.Thread(target=other_things())
restp.start()
musicp.start()
LIke you can see i even tried multithreading but it still waits until the music is over before it goes to the rest of the code.
Don't call the functions in the target parameter of the Thread function - delete the brackets to reference the function, not its return value
musicp = threading.Thread(target=music) # instead of music()
restp = threading.Thread(target=other_things) # instead of other_things()
I want to start another process, it will start, if I write to telegram bot "start". But right after this occurring the ERROR:
2022-04-11 11:16:13,602 (__init__.py:688 Thread-1)
ERROR - TeleBot: "A request to the Telegram API was unsuccessful. Error code: 409.
Description: Conflict: terminated by other getUpdates request;
make sure that only one bot instance is running"
I am running ONLY one bot at the same time, already checked it. I found, that the error occurs when program trying to start a new process. Could anyone help me, please?
from time import sleep
from datetime import datetime, timedelta
import telebot
from telebot import types
from threading import Thread
import multiprocessing
def collecting(a):
while True:
print(a)
sleep(3)
if __name__=='__main__':
bot = telebot.TeleBot(token)
workers = []
def listen():
#bot.message_handler(content_types='text')
def get_text(message):
id = message.chat.id
mes = message.text
if mes=='start':
bot.send_message(id, 'okey')
workers.append([str(datetime.now())])
else:
bot.send_message(id, mes)
bot.polling()
Thread(target=listen).start()
while True:
sleep(1)
x = workers[:]
for i in range(len(x)):
multiprocessing.Process(target=collecting, args=(x[i],)).start()
del workers[i]
UPD: Forgot to say, this error occurred only when I create exe file and run this code like exe program. This is how I create exe file:
pyinstaller --hidden-import=pkg_resources.py2_warn --onefile Program.py
Solved, I forgot to add this:
from multiprocessing import freeze_support
And then after if__name__=="__main__": also need to write freeze_support().
I've been trying to make loops in Discord.py, but I keep failing. What makes it harder is that it returns no errors.
This is the code;
import discord
import datetime
import time
import threading
import os
import json
import random
import asyncio
from discord.ext import commands
from discord.ext.commands import has_permissions
from discord.ext.tasks import loop
import keep_alive
prefix = "s."
token = str(os.getenv("TOKEN"))
client = commands.Bot(command_prefix = prefix)
client.remove_command("help")
os.chdir(r".")
ownerId = [219567539049594880]
logChn = 705181132672729098
secondsUp = 0
#loop(seconds=1)
async def add_second():
secondsUp+=1
print("+1 Second")
The console does not print anything. No errors. Is there anything I'm missing?
In discord.py, you must call the .start() method on every loop that you create. In this case, add_seconds.start(). Also, try adding global secondsUp to the top of your function definition.