Telegram API throwing PeerFloodError: Too many requests - python-3.x

I am not using bot API. I am using Telegram API to send messages. Messages are being sent easily but the problem occurs after 19 users. On the 20th user, I receive PeerFloodError. Even after, searching a lot, I didn't find any specific limits and using sleep is not working either. Please suggest a way to overcome this problem.
Code
def send_message(root2, client):
totalcount = 0
for user in users:
if totalcount >= len(users):
root2.destroy()
break
if totalcount % 15 == 0 and totalcount != 0:
print("Waiting for one minute...")
time.sleep(60)
if user not in users2 or user not in users3:
totalcount += 1
entity = client.get_entity(user)
client.send_message(entity, message_str)
time.sleep(8)

most of the Telegram APIs have strict limits for each of 30-seconds, 30-minutes, 24-hours periods. spread 19(or less API calls in 30 minutes and catch whether it throws an error or not, if it's doing fine after 30minutes: Great! otherwise, do this process for 24 hours.)
note that for a bulk usage of Telegram APIs, you may need to use several accounts in your project.

Related

pyTelegramBotAPI inline google search engine

#bot.inline_handler(func=lambda query: len(query.query) > 0)
def query_text(query):
sleep(6)
text=query.query
html=requests.get(f'https://google.com/search?q={text}')
# print(html.status_code)
open('index.html','w', encoding='utf-8').write(html.text)
soup=BeautifulSoup(html.text, 'html.parser').find_all('div',{"class":"***********"})
for i in soup:
fk.append(types.InlineQueryResultArticle(id=str(len(fk)), title=f"{i.find('h3').get_text()}",description=f"{i.find('div',{'class':'**********'}).get_text()}",input_message_content=types.InputTextMessageContent(message_text=i.find('a').get('href').replace('/url?q=','https://google.com/url?q=')),hide_url=True,url=i.find('a').get('href').replace('/url?q=','https://google.com/url?q='),thumb_url='https://w7.pngwing.com/pngs/338/520/png-transparent-g-suite-google-play-google-logo-google-text-logo-cloud-computing.png', thumb_width=30, thumb_height=30))
print(i.find('a').get('href').replace('/url?q=','')+'\n')
sleep(2)
bot.answer_inline_query(query.id, fk)
When I write #bot google request
Bot takes it as g go goo google
What is causing the error
"A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: query is too old and response timeout expired or query ID is invalid"
How to make text input timeout so that it doesn't respond to every letter?
I think, the error resides in your way of parsing data. It takes at least 8 seconds (based on sleeps) just to get to the answer method. Telegram inline queries have very few seconds until they are considered old, so, it is better to process data after you call bot.answer_inline_query() and then send it to user using bot.send_message()
I am not certain how it works with async code though.
If you find another solution, please let me know :)

Timestamp For Discord Bot Status

I am using Discord.js Node V12 I am currently trying to find out how to say time elapsed in the status to show how long the bot has been playing game or any activity. But i cannot find anyone who has asked or answered any of these questions.
#client.event
async def on_connect():
await client.change_presence(status=discord.Status.dnd,activity = discord.Game(name = "VALORANT"))
I would like to break this answer into a few significant points:
• The sample code provided is from discord.py ( a discontinued python based library to interact with the API ) which is totally out of context of the whole question itself since you're asking it for discord.js
• There is no actual way to find the time elapsed since a particular activity as of now but you may resort to this:
var uptime = client.uptime; // returns uptime in milliseconds
var hours = uptime / 1000 / 60 / 60 // converts it to hours
/*
Then you may apply the following approach to change your status every hour passes
*/
setInterval(() => {
client.user.setActivity(`Valorant since ${hours} hour(s)`);
}, 3600000); // this would show up as Playing Valorant since 1 hour(s) and subsequently would change every hour if your bot isn't being restarted continuously.
I took a look at the discord.js documentation to examine setting activities and found no such information about timestamps. However, there was a section in the ActivityType that led me to the discord developers documentation and it indicates:
Bots are only able to send name, type, and optionally url.
So it doesn't seem as though you will be able to set the start or end timestamps for an activity as a bot.

NodeJS | Python | Heroku - Scheduling Emails 48 Hours after form Post

I've made a PWA with ReactJS + NodeJS, running with a python backend that's being spawned as a child process by the Node server, I have to send and generate a document generated by python via email 48 hours after payment verification is called, how do I accomplish this? My current method includes :
def sendInTwoDays(recipient, filename):
time = round(random.uniform(0.8, 2.0), 2)
time = round(time * 24 * 3600, 2)
time /= 10000 #for testing
print("[python:sendInTwoDays()] > Sleep ({} seconds) : {} days".format(time, time/3600))
sleep(time)
sendNow(recipient, filename)
I hate it since it uses "sleep()" and sleep on a webserver just doesn't sit right with me.
Please suggest a better way to accomplish the same on heroku.
I would suggest a scheduling(cron) approach with Heroku Scheduler like to check due emails every fifteen minutes. Rather than letting the process sit for 48 hours, I would save the email data along with the emailing time in the database and let the scheduler can invoke an API/task to call the Python script to output and email documents which are due after 48 hours.
The emails will not be sent out after exact 48 hours, but should be close.

How do I schedule a task to run every x hours using cron? Discord.py

Basically, what I want to do is use the package aiocron to schedule an automatic reboot every 5-8 hours because I've noticed some tasks just stop functioning after a certain amount of time being online. I don't know why they stop but they do, I'm not getting any errors either, weirdly enough. If you want the code to the task I'm talking about, here it is:
#tasks.loop(count=None, minutes=2.5)
async def autoh(self):
await self.bot.wait_until_ready()
with open("autoposting.json", 'r') as f:
auto = json.load(f)
embed = discord.Embed(title="Enjoy your poggers porn lmao",
description=f"Posting can be slow, please take into consideration how many servers this bot is in and how many are using auto posting. Please be patient. If I completely stop posting, please rerun the command or join the support server.\n[Add me]({Invite}) | [Join the server]({Server}) | [Vote]({Vote})", colour=EMBED_COLOUR)
try:
embed.set_image(url=(await self.get_hentai_img()))
except nekos.errors.NothingFound:
return print("no image found")
else:
for entry in auto.items():
if "hentai_channel" in entry[1]:
channel = self.bot.get_channel(
entry[1]["hentai_channel"])
await asyncio.sleep(2)
if channel != None:
if not channel.is_nsfw():
await channel.send(f"This channel seems to not be NSFW anymore.\nThis message will continually repeat until you fix this issue.")
else:
try:
await channel.send(embed=embed)
except discord.Forbidden:
#pass
await channel.guild.owner.send(f"I was unable to autopost due to missing permissions in {channel.guild.name}, please check that the channel still exists and that I have the permission to post to it.\nThis message will continually repeat until you fix the issue at hand.")

A way to get discord bot to send a private message at a set time?

This is my first discord bot I have created, and it is for an idea that is complicated but I find as fun. I was wanting to create a discord bot that can send private messages to random users at a certain time (in my case, once every 24 hours). Is there a way to code this? I am using Node.js/nodemon to run the code. I already have the bot running and online, I just need a way to do what I was hoping to accomplish! Thank you to anyone who could help me out with this!
I would do setTimeout of some sort if you have your bot hosted 24/7.... If not I would find some sort of npm package that shows the time and then do
if(npmpackagetime == 'Whatever time you want here') return user.send('Your message here')
And if you want to chose a random user, make an array of all the guild's users and then do let newUser = Math.floor(Math.random() * arrayName.length); and then newUser.send('Your message here');

Resources