Error 409 occurred in telebot when using multiprocessing [exe file] - python

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().

Related

Why does the TelegramBot get stuck when executing Inline commands?

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

Python, how to execute a line of code without it stopping the rest of the code from executing?

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()

the loop of sending messages python-telegram-bot-api aiogram

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")

I need a Major schedule file and inside that i also needed to run a sub schedule file,how can i do that?I tried crontab to schedule major

i am not able to schedule the sub schedule file(run only at once)
30 1 * * * python3 majorfile.py
the major file is scripted like this
import datetime
import time
import schedule
if today == some specific date:
def run1():
exec(open('sub_file.py').read())
return schedule.CancelJob
schedule.every().day.at("5:30").do(run1)
(this job is needed to run once)
with second the part i am facing issue(in this part also have situations like concurrent events)....it is not running....can anyone help me in this?'''
Error:-
The works pending must be checked in a loop.
Code:-
import datetime
from time import sleep
import schedule
def run1():
exec(open('sub_file.py').read())
return schedule.CancelJob
schedule.every().day.at("5:30").do(run1)
while True:
schedule.run_pending()
sleep(1)

AttributeError: module 'apscheduler.schedulers.asyncio' has no attribute 'get_event_loop'

I am trying to implement clock process to use in Heroku dyno. I am using Python 3.6. Clock process will run each 3 hours. This is the code:
import os
import sys
import requests
from apscheduler.schedulers import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.triggers.interval import IntervalTrigger
from webdriverdownloader import GeckoDriverDownloader
from scraper.common import main
def get_driver():
return True
def notify(str):
return True;
if __name__ == '__main__':
scheduler = AsyncIOScheduler()
get_driver()
scheduler.add_job(main, trigger=IntervalTrigger(hours=3))
scheduler.start()
# Execution will block here until Ctrl+C (Ctrl+Break on Windows) is pressed.
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait())
except (KeyboardInterrupt, SystemExit):
pass
At first I tried with
asyncio.get_event_loop().run_forever()
However, I read that this is not supported in python 3.6, so I changed this statement to run_until_complete.
If I run this example, the code prints out:
AttributeError: module 'apscheduler.schedulers.asyncio' has no attribute 'get_event_loop'
Does anyone know why this error occurs? Any help would be much appreciated. Thanks in advance!
You're not importing the asyncio module from the standard library but the asyncio module in the apscheduler library. You can see that by visiting the link here.
There are only two things you can import from that namespace:
run_in_event_loop
AsyncIOScheduler
If you need to use the low-level asyncio API just import asyncio directly from the standard library.

Categories

Resources