Содержание
- Any Way To Avoid Telegram Flood Prevention ? #474
- Comments
- Error when adding Members to group. #1290
- Comments
- Getting flood error from telegram. script is stopping now. please try again after some time. jobs
- Filter
Any Way To Avoid Telegram Flood Prevention ? #474
I Sending Massive Messages To Telegram But I Get Flood Prevention And I Have to wait.
I Used Thread.Sleep() Between My Messages But I Get Same Results . Any Way To Avoid This?
The text was updated successfully, but these errors were encountered:
Me too, have this problem and thread.sleep can’t help.
I’m using try-catch block and in catch block, using thread.sleep(exception.TimeToWait), but with this way, application freez for second such as 200s.
No solution . 🙁
can you tel me, when u get this error ? in sendmessage method I’m try to send to 100 users successful without error.
Is wait for 9800 seconds reasonable?
I have no problems with the next code:
Flood prevention. Telegram now requires your program to do requests again only after 9792 seconds have passed (TimeToWait property). If you think the culprit of this problem may lie in TLSharp’s implementation, open a Github issue please.
.
@mostafa8026 do you think this problem lies in TLSharp? If yes, explain why, please.
Obviously it’s a limitation imposed by Telegram API, in order to prevent non-human users from causing chaos and anarchy in the network.
Although the details about this limitation hasn’t been officially specified, it seems the only solution is to find a way (maybe waiting longer between requests or distributing them etc.) to send less requests in a unit of time overall.
@hosseinGanjyar you know, the telegram official Windows client is opensource too, and that one doesn’t suffer these problems I guess. You could debug it, and try to figure out what’s the difference between its implementation and TLSharp? (Or your app which consumes TLSharp API)
Hi, any solution found here ?
Thanks
@FarhadMohseni did you found a solution for your problem ?
No,This is a Telegram Api Limitation.
I already have this while debugging login / auth issues. I have to wait 77943 seconds, that is over 21 hours. I have no loops, just manual starts, less than 100.
@hosseinGanjyar
It is great that you have found a solution to this . if I am understanding correctly there should be a random waiting time between requests? Right?
Because I am using a fixed waiting time but still having the issue.
btw I am using Python Telethon API
Thank you
@hosseinGanjyar Thank you!
is there a minimum amount for the random waiting?
@hosseinGanjyar Hello! I made this delay, but I still have this error. Why?
@ahasna can you share us a little bit experience about the waiting time?
I have to wait about 10 hours. Did anyone find a solution?
How did you solve. can you share. we have this error.
Why a new issue?
One way to circumvent this problem is to create multiple telegram clients from different phone numbers. Then call the API in round robin fashion from each client so that requests are distributed evenly
I have got an idea and solution. How many timesdo you call an API?
And which one of API? (name)
Please share sample code. I will help you.
Me too, have this problem and thread.sleep can’t help.
I’m using try-catch block and in catch block, using thread.sleep(exception.TimeToWait), but with this way, application freez for second such as 200s.
No solution . 🙁
can you tel me, when u get this error ? in sendmessage method I’m try to send to 100 users successful without error.
I got ‘Getting Flood Error from telegram. Script is stopping now. Please try again after some time.’ after only 4 message and then after waiting for hours still not able to send. Any suggestion
Can u tell me how to use this . Bcoz i use another script i am getting flood error
Has anyone found a optimisation time to avoid the PEER FLOOD ERROR?
There is not such thing. It is completely on telegram algorithm that manage this time. you have to write the program for a general use, not spam 😉
Источник
Error when adding Members to group. #1290
Have this problem and absoulety no clue after searching 1 week for a solution. Im not a professionell so maybe its a little bit hard to solve it. Your help would be so great. 😉 I try to add Telegram Group User to another group. Scraping those names is no problem. But adding gives me this error. Thanks so much!
from telethon.sync import TelegramClient
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser
from telethon.errors.rpcerrorlist import PeerFloodError, UserPrivacyRestrictedError
from telethon.tl.functions.channels import InviteToChannelRequest
import sys
import csv
import traceback
import time
import random
api_id = ‘xxx’
api_hash = ‘xxx’
phone = ‘+xxx’
client = TelegramClient(phone, api_id, api_hash)
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone)
client.sign_in(phone, input(‘Enter the code: ‘))
users = []
with open(r»C:UsersAdministratorDocumentsTelegram scrapermembers.csv», encoding=’UTF-8′) as f:
rows = csv.reader(f,delimiter=»,»,lineterminator=»n»)
next(rows, None)
for row in rows:
user = <>
user[‘username’] = row[0]
user[‘id’] = int(row[1])
user[‘access_hash’] = int(row[2])
user[‘name’] = row[3]
users.append(user)
chats = []
last_date = None
chunk_size = ‘200’
groups=[]
result = client(GetDialogsRequest(
offset_date=last_date,
offset_id= 0,
offset_peer=InputPeerEmpty(),
limit=chunk_size,
hash = 0
))
chats.extend(result.chats)
for chat in chats:
try:
if chat.megagroup== True:
groups.append(chat)
except:
continue
print(‘Choose a group to add members:’)
i= 0
for group in groups:
print(str(i) + ‘- ‘ + group.title)
i+= 1
g_index = input(«Enter a Number: «)
target_group=groups[int(g_index)]
mode = int(input(«Enter 1 to add by username or 2 to add by ID: «))
for user in users:
n += 1
if n % 50 == 0:
sleep(900)
try:
print («Adding <>«.format(user[‘id’]))
if mode == 1:
if user[‘username’] == «»:
continue
user_to_add = client.get_input_entity(user[‘username’])
elif mode == 2:
user_to_add = InputPeerUser(user[‘id’], user[‘access_hash’])
else:
sys.exit(«Invalid Mode Selected. Please Try Again.»)
client(InviteToChannelRequest(target_group_entity,[user_to_add]))
print(«Waiting for 60-180 Seconds. «)
time.sleep(random.randrange(60, 180))
except PeerFloodError:
print(«Getting Flood Error from telegram. Script is stopping now. Please try again after some time.»)
except UserPrivacyRestrictedError:
print(«The user’s privacy settings do not allow you to do this. Skipping.»)
except:
traceback.print_exc()
print(«Unexpected Error»)
continue
The text was updated successfully, but these errors were encountered:
Источник
Getting flood error from telegram. script is stopping now. please try again after some time. jobs
Filter
My recent searches
Filter by:
Budget
- Local Jobs
- Featured Jobs
- Recruiter Jobs
- Full Time Jobs
Skills
Languages
Job State
We’re looking for a senior person that has sufficient knowledge of websockets, networking and Go/Rust. Task includes replacing the current server side web socket library from Rust to Go. You must have the following: 1) At least 5+ years experience in backend development 2) Sound knowledge of low level networking protocols. TCP/UDP/Websockets 3) Must have working level experience in Go/Rust 4) Must have Bachelors in Computer Science or equivalent. No fake profiles, we’ll catch them quick so don’t waste time. No agencies. Send your proposals.
Design pictures, remove backgrounds from pictures
I would like to have the HTML/CSS code in an easy way to edit it and publish it any time with similar information. I will use Highcharts to create the graphs. I’d like to know where I need to put the Highcharts JS Code in my html for the graph to use the designed space for charts. My web is: The desire format is: :
:text=UNCTAD%20projects%20global%20maritime%20trade,during%20the%20past%20three%20decades. My current mix of both is An example of some Highcharts, that I will to put in the page instead of the actual ones. Issues that I loved from the desire webpage: The possibility to put a small video or an image gif. I just need that you
Our QA team is looking for a virtual assistant from united states now. You must be based on United States and are living in United States currently. Please apply if you are able to assist us. Thank you
Hello, i search a specialist for a video editing script. I have on a web server videos that customers upload from their phones. These files we need: Preparing: Save in web format (convert from apple, android. ) and compress 1. Put together that we have one file 2. Put text on the video (overlay) 3. Create a text to speech file and insert 4. Put music file on 5. Put Image or video on the end 6. Save in different formats. Desktop 16:9, Mobile 9:16 optimized This complete automated, in what for a programming language, is up to you, but i need the source code and comments inside. If you have idea how you will do this, write me: «Hey Dennis, i have idea how i will do it» first in your answer because here are so many bots. Try to make a fix .
Prestashop error 500 backend when i try to install module or update
. Objective: To design and develop a hardware device that can remove laser printer ink from paper at specific locations. Scope: • The device should be able to identify and target specific areas of the paper where the ink needs to be removed. • The device should be able to remove the ink without damaging the paper or causing smudging. • The device should be easy to use and have a user-friendly interface. • The device should be able to handle various types and sizes of paper. • The device should be portable and easy to transport. Hardware Requirements: • High-powered laser capable of removing laser printer ink from paper. • Camera for image recognition to identify specific areas of the paper where ink removal is needed. • Control .
Need to Migrate All Emails from Gsuite to Office365 Outlook Just 3-4 EMails with Less Data.
Please Sign Up or Login to see details.
Have 5-10 sites with mails and that need to transfer to another server. Take the job only if you have migrated from plesk to cpanel before. and have good expierience with mysql Databases, wordpress Dns settings etc.
I have a working p. of 2 pages, except for 1 part. This project has a user that is logged in and chooses a name from a drop down menu. Once they do this, they click a button to send one of their existing tokens to someone else. The result is that the user has one token subtracted, and the second user has one token added. This project already works for having one token subtracted from the user, and the transaction information sending to 2 different databases for record keeping and back up. The only part that doesn’t work is getting the token added to the person that is selected in the drop down menu. Note: I cannot restructure the database in any way. Everything is in place that is needed. For someone skilled, this should .
Hi tahaAbodia96, I noticed your profile and would like to offer you my need a resident or citizen in Tripoli, Libya to obtain a police certificate for my fiance who is in the process of getting an immiigration visa to the US. We need person to go to the police with the information we give to them and get a police certificate. We need the police certificate sent by DHL, Fedex or international to Fes, Morocco where my fiance is currently living.
want telegram organic promotion messaging promotion
We need a full time script writer for Short Content like Reels & Shorts. Preference for North Indians ( Delhi, Haryana & Punjab). We’ll pay according to the quality of Script. Anyone Interested can contact me.
#PART_TIME * Working Part time 20 hour / week. * Price: 8000 INR / Month #GENERAL_RULES * Committed to the times of attendance and departure on working hours. * Uses a program that monitors the computer screen while working.
Need a fictional artwork of a couple looking into each other’s eyes sitting on the beach in a sunset lit scene. Reference photo of the style expected in the painting is attached below, but that is not exactly to be copied
Hello, i have to copy in white label a crypto coin swap. You have to take the source code, add my own Api key and make it work on telegram. Thats it 🙂 More information before placing the bid in DM
I want to make a one page flyer for time time attendance machine. basically the flyer will show an old time punch in card (I attached as an example) and a new time attendance biometric (Attached) and the benefits that you will get from moving from the old system to the new Record the time for employee in and out export the form into excel format no need for software No Subscription One time fee starting of $375 100% employee identity verification with every single punch; built in camera to provide photo verification even in instance of failed finger scan. make it easier for the payroll process electronic and verified record of employees attendance Simplify the onboarding process when you register and pair your employee’s f.
We want to design a new audio PCBA for a headset We need high quality cristal voice See attached specs
I’m currently looking to know how much bringing on a full time writer into my team would be. I have a number of web assets that need content on an ongoing basis and these are mainly in the travel and food and drink sector. I’m primarily looking for people with excellent English spelling and grammar and also people who are confident in writing engaging, well structured content that helps to keep people on my sites. I’m not adverse to using AI tools like Jasper to generate content so long as any AI content gets pushed through a tool like Quillbot / Grammarly first. So the main things I’m looking for in your quote / message back, and to make sure you have read my message, are how much your time would be for the month and an estimate of how much content yo.
Happy New Year! Hope you are fine and doing great! Here is the first job of this new year to translate into the above mentioned languages. The word break-ups are given in the analyze file and it is for Tuesday 17th January EOB delivery. I’ll appreciate it if your resources can take care of the task and deliver the high quality translations. 1. Kindly translate using the Trados package and deliver the return package once you are done with the translation. 2. Keep the consistency in phrases/terms throughout the file by using the same already existing in the files. 3. Please have a final look at your translation before delivery to make sure the translation is error free and no issues are left.
Read 4 chapters ( 80 pages) of a book on bilingualism and write summaries in easy English so English learners can understand the book more easily. If you can start reading asap — start writing down bullet lists of what’s written in easy english and send as you write, that would be perfect. (She needs to have read those chapters and written an essay on each chapter by the end of Jan 14 USA time, so, if you could help her read it she can work on each essay as the day goes by.)
I want to export raw P&L data from QB into 3 separate monthly P&L statements by department, into a nice, easy to read, formatted P&L statement for each of 3 departments
I’m looking for someone that is familiar with telegram and knows how to scrape groups and add the members to our group. Please only bid if you know how to accomplish this. To start with just a few smaller groups with maybe 300 members.
i have a script needs to edit to ninjatrader 8
We need Unity Game Expert who can add new payment gateway in frontend and backend, Internal Chat in players and Normal Registration page. currently in game we use google sign in option. In current game already other payment gateway but we want another one Backend is in PHP And Game name is Ludo Don’t expect high amount
There is a trading strategy code, it needs to be rewritten into the python language with the programming of the trading bot.
This is a 880 word survey that needs to be translated.
i dont want to get duplicate people in python ! , my python is getting duplicate people same profile i mean , so what i want to do is remove duplicate people and dont waste time for this ! remember im not going to award or milstone since ill check and test in my computer ! i know its trust issues but if you can do im here
Our company uses SAP By Design as an ERP system. We have several customer accounts that have open items that we would like to clear against each other. In the UI, we would have to go account by account and manually post the clearing. However, there is an option through the SAP Cloud Applications Studio to clear open items using the DueClearingUtilities.ClearOpenItems. We need assistance to build and test this script.
The website will be named «zercos» (obviously no quotation marks) The website will be themed mostly around visitors getting free stuff (zero cost -> zercos) The logo should be flat, modern and somewhat look like a tech firm. the logo must include: logo logo negative app symbol all in vector format (.ai and .svg) no gradients, no shadows. preferrably in a dark green or petrol green colour. Two colours may be used but not more.
I need an animator, I have the storyboard ready and just need to do the animation within 2 days.
I am trying to implement gas sensor using COMSOL. The structure is ready but laminar physics is not working. as soon as this physics is applied, an error message appears. pic attached for reference. can anyone help me with this. in addition to that, i want to plot the following graphs a) Resistance vs concentration b) Concentration and flux plots c) Resistance vs time d) Concentration vs time e) Response vs time f) Adsorption and desorption process the designed structure and required velocity profile is also attached
Dear Designer , I need designer who can create logo for my shop by use reference from shopee logo () . what you need to do is only 1. Change S in basket to D 2. Change Shopee to elifresh Please provide .ai and .png size 4096×1309 when project complete
I have my virtual tour, need a duplicate of this to scale, exactly. all I have is this virtual tour, so the artist can see what needs to be done.
any emails sent to gmail from CWP server are rejected with message : «has an SPF record with a hard 550-5.7.26 fail policy (-all) but it fails to pass SPF checks with the ip: 550-5.7.26. » Need to fix this. .
hi i have a python program but the requests are getting blocked by google so i want someone to add proxies to it.
Hi Chandrasekhar G., You asked for more work, I have something for you
Create a Pipeline which consume data from Upstream Salesforce and Order Management System. The data get store at MongoDB and after some aggregation it generate Dashboard on External Third party system connected via API. Must Be Experience in Java Script , NodeJS, Express , AngularJS and Mongo
Building an urgent care facility and would like the floor plan to be put in 3d before getting the engineering drawing done.3000 square foot building with typical layout.. land work and parking area will be included in project.
I will create a floorplan to renovate your old storage building into a loft 75 year old parents. I will implement the following within the space at minimum: A kitchen with, — sink — oven/stovetop — seating area for 4 people. Bedroom with, — 5ft bed with access both sides — stora. A kitchen with, — sink — oven/stovetop — seating area for 4 people. Bedroom with, — 5ft bed with access both sides — storage — dressing table — bed situated where you can get in and out without hitting your head. Bathroom with, — a big walk in shower — big sink (double vanity) Things I will try to put into the floorplan if possible include: Kitchen with, — Island with stools rather then a table A living room/ sitting area with, — 2 sofas — TV Finally, you want a functional space that is.
Hi Cornelia T., I noticed your profile and would like to offer you my project. We can discuss any details over chat.
fixing bugs in marriage website. Freelancers from Mumbai only.
I am trying to create a game that runs the emulator in docker compose and is based on the swf practically the entire game
I am looking for someone based in India who can help me with building an app in the wealth tech space. The ideal candidate should have sound knowledge of UI/UX design as well as experience in product management. Please share your past projects that you would have created in the similar domain
Change php Version in my WordPress website PHP update from 7.4 to 8.1
Please design us a flyer for the «4×4 Club Mud Fest». Portrait a4 size. The whole event is about driving cars through the mud and getting messy. FUN IN THE MUD! 12th Feb 2023 Starting 8am Venue: Donnybrook $5 entrance Cooler boxes allowed Mudslinging, tug o’ war, pit courses and more! Contact Ryan 0771234567 Please see image and logo attached
i want some onw write to me script php 3 page
My trust wallet is infected by an automatic withdrawal bot and I can’t get the TRX in it needed to withdraw the funds, I need you to remove the bot from it and please cashoit the USDT TRC20 in it and send to o my cashapp/Bitcoin wallet. I received the trust wallet as payment for back rent I am owed by a tenant and have no idea what I’m doing with it. I don’t even know for certain there’s such a thing as this bot, it’s what Ive been told. I’m also told that binance is the best way to do it but I have no idea.
Hello! We are an LLC company in DELAWARE, USA, consisting of two members, who are tax residents of Greece. The company was incorporated in March 2022, has an EIN, and in 2. company in DELAWARE, USA, consisting of two members, who are tax residents of Greece. The company was incorporated in March 2022, has an EIN, and in 2022 had no revenue (zero revenue), no expense, and no employees. We need an accountant to prepare and submit the tax return to the IRS for 2022. At the present stage, we are interested in reasonable and fair remuneration, precisely because there is no income from our side. We hope that 2023 will be a better period for the company, and that’s why we need an accountant with whom we would like to cooperate in the future. We look forward to your suggestions.
Источник
I dont know what’s wrong, but I’m stuck on making my program. Does anyone have any ideas about this?
This is the error I’m getting:
*Traceback (most recent call last):
File "C:UsersAdministratorDesktopTelegram Marketingadd members in channeladd members.py", line 50, in <module>
user_to_add = client.get_input_entity(user['username'])
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonsync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "c:usersadministratorappdatalocalprogramspythonpython38libasynciobase_events.py", line 616, in run_until_complete
return future.result()
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 404, in get_input_entity
await self._get_entity_from_string(peer))
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 516, in _get_entity_from_string
result = await self(
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 47, in __call__
raise errors.FloodWaitError(request=r, capture=diff)
telethon.errors.rpcerrorlist.FloodWaitError: A wait of 71180 seconds is required (caused by ResolveUsernameRequest)
Unexpected Error *
My code:
channel = client(GetFullChannelRequest(channel_username))
mode = 1
for user in users:
try:
print ("Adding {}".format(user['id']))
if mode == 1:
if user['username'] == "":
continue
user_to_add = client.get_input_entity(user['username'])
else:
sys.exit("Invalid Mode Selected. Please Try Again.")
client(InviteToChannelRequest(channel,[user_to_add]))
print("Waiting 60 Seconds...")
time.sleep(60)
except PeerFloodError:
print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
time.sleep(900)
except UserPrivacyRestrictedError:
print("The user's privacy settings do not allow you to do this. Skipping.")
except:
traceback.print_exc()
print("Unexpected Error")
continue
Я не знаю, что не так, но я застрял на создании своей программы. Есть у кого-нибудь идеи по этому поводу?
Я получаю вот такую ошибку:
*Traceback (most recent call last):
File "C:UsersAdministratorDesktopTelegram Marketingadd members in channeladd members.py", line 50, in <module>
user_to_add = client.get_input_entity(user['username'])
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonsync.py", line 39, in syncified
return loop.run_until_complete(coro)
File "c:usersadministratorappdatalocalprogramspythonpython38libasynciobase_events.py", line 616, in run_until_complete
return future.result()
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 404, in get_input_entity
await self._get_entity_from_string(peer))
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 516, in _get_entity_from_string
result = await self(
File "c:usersadministratorappdatalocalprogramspythonpython38libsite-packagestelethonclientusers.py", line 47, in __call__
raise errors.FloodWaitError(request=r, capture=diff)
telethon.errors.rpcerrorlist.FloodWaitError: A wait of 71180 seconds is required (caused by ResolveUsernameRequest)
Unexpected Error *
Мой код:
channel = client(GetFullChannelRequest(channel_username))
mode = 1
for user in users:
try:
print ("Adding {}".format(user['id']))
if mode == 1:
if user['username'] == "":
continue
user_to_add = client.get_input_entity(user['username'])
else:
sys.exit("Invalid Mode Selected. Please Try Again.")
client(InviteToChannelRequest(channel,[user_to_add]))
print("Waiting 60 Seconds...")
time.sleep(60)
except PeerFloodError:
print("Getting Flood Error from telegram. Script is stopping now. Please try again after some time.")
time.sleep(900)
except UserPrivacyRestrictedError:
print("The user's privacy settings do not allow you to do this. Skipping.")
except:
traceback.print_exc()
print("Unexpected Error")
continue
1 ответ
Лучший ответ
Попробуй это:
client(InviteToChannelRequest(channel_username,[user['username']]))
GetFullChannelRequest возвращает ChatFull, и использование его в качестве входных данных для InviteToChannelRequest вызовет ошибку типа. Все, что похоже на сущность , будет работать.
- Ссылка для приглашения канала
- Имя пользователя канала
- ID пользователя канала
Может использоваться как аргумент канала для InviteToChannelRequest. также,
- имя пользователя,
- ID пользователя,
- телефонный номер
Будет работать для аргумента пользователей.
0
Goodarzi
20 Апр 2020 в 07:57
var store = new CustomSessionStore();
client = new TelegramClient(apiId, «apiHash», store as
ISessionStore, «session», new
TLSharp.Core.Network.TcpClientConnectionHandler(conectarProxy));
await client.ConnectAsync();
if (client.IsConnected)
{
if (await client.IsPhoneRegisteredAsync(countryPrefix +
phoneNumber))
{
if (!client.IsUserAuthorized())
{
hash = await
client.SendCodeRequestAsync(countryPrefix + phoneNumber); //request for
session creating
var user = await client.MakeAuthAsync(countryPrefix
+ phoneNumber, hash, «xxxxx»);
}
}
resultContact = await client.GetContactsAsync();
}
////////////////////////////////
public class CustomSessionStore : ISessionStore
{
public void Save(Session session)
{
var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
«Sessions»);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
var file = Path.Combine(dir, «{0}.dat»);
using (FileStream fileStream = new
FileStream(string.Format(file, (object)session.SessionUserId),
FileMode.OpenOrCreate))
{
byte[] bytes = session.ToBytes();
fileStream.Write(bytes, 0, bytes.Length);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////
private TcpClient conectarProxy(string httpProxyHost =
«127.0.0.1», int httpProxyPort = 8580)
{
var url = «http://» + httpProxyHost + «:» + httpProxyPort;
var proxyUrl = WebRequest.DefaultWebProxy.GetProxy(new
Uri(url));
WebResponse response = null;
var tentativas = 10;
while (tentativas >= 0)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
var webProxy = new WebProxy(proxyUrl);
request.Proxy = webProxy;
request.Method = «CONNECT»;
request.Timeout = 3000;
tentativas—;
try
{
response = request.GetResponse();
break;
}
catch (Exception ex)
{
if (tentativas >= 0 && ex.Message.Equals(«The operation
has timed out», StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(«Ocorreu timeout ao tentar se
conectar pelo proxy.»);
}
else
{
throw new Exception(«Algo deu errado», ex);
}
}
}
var responseStream = response.GetResponseStream();
Debug.Assert(responseStream != null);
const BindingFlags Flags = BindingFlags.NonPublic |
BindingFlags.Instance;
var rsType = responseStream.GetType();
var connectionProperty = rsType.GetProperty(«Connection»,
Flags);
var connection = connectionProperty.GetValue(responseStream,
null);
var connectionType = connection.GetType();
var networkStreamProperty =
connectionType.GetProperty(«NetworkStream», Flags);
var networkStream = networkStreamProperty.GetValue(connection,
null);
var nsType = networkStream.GetType();
var socketProperty = nsType.GetProperty(«Socket», Flags);
var socket = (Socket)socketProperty.GetValue(networkStream,
null);
return new TcpClient { Client = socket };
}
…
Any Way To Avoid Telegram Flood Prevention ? #474
Comments
FarhadMohseni commented May 13, 2017
I Sending Massive Messages To Telegram But I Get Flood Prevention And I Have to wait.
I Used Thread.Sleep() Between My Messages But I Get Same Results . Any Way To Avoid This?
The text was updated successfully, but these errors were encountered:
mehdiyahyavi commented May 16, 2017 •
Me too, have this problem and thread.sleep can’t help.
I’m using try-catch block and in catch block, using thread.sleep(exception.TimeToWait), but with this way, application freez for second such as 200s.
No solution . 🙁
can you tel me, when u get this error ? in sendmessage method I’m try to send to 100 users successful without error.
mostafa8026 commented Jul 3, 2017
Is wait for 9800 seconds reasonable?
re-al-7 commented Jul 5, 2017
I have no problems with the next code:
mostafa8026 commented Jul 9, 2017
Flood prevention. Telegram now requires your program to do requests again only after 9792 seconds have passed (TimeToWait property). If you think the culprit of this problem may lie in TLSharp’s implementation, open a Github issue please.
.
knocte commented Jul 9, 2017
@mostafa8026 do you think this problem lies in TLSharp? If yes, explain why, please.
dozham commented Jul 15, 2017
Obviously it’s a limitation imposed by Telegram API, in order to prevent non-human users from causing chaos and anarchy in the network.
Although the details about this limitation hasn’t been officially specified, it seems the only solution is to find a way (maybe waiting longer between requests or distributing them etc.) to send less requests in a unit of time overall.
knocte commented Jul 22, 2017
@hosseinGanjyar you know, the telegram official Windows client is opensource too, and that one doesn’t suffer these problems I guess. You could debug it, and try to figure out what’s the difference between its implementation and TLSharp? (Or your app which consumes TLSharp API)
mHCio commented Aug 3, 2017
Hi, any solution found here ?
Thanks
mHCio commented Aug 3, 2017
@FarhadMohseni did you found a solution for your problem ?
FarhadMohseni commented Aug 3, 2017
No,This is a Telegram Api Limitation.
ghost commented Sep 28, 2017
I already have this while debugging login / auth issues. I have to wait 77943 seconds, that is over 21 hours. I have no loops, just manual starts, less than 100.
ahasna commented Oct 7, 2017 •
@hosseinGanjyar
It is great that you have found a solution to this . if I am understanding correctly there should be a random waiting time between requests? Right?
Because I am using a fixed waiting time but still having the issue.
btw I am using Python Telethon API
Thank you
ahasna commented Oct 8, 2017
@hosseinGanjyar Thank you!
is there a minimum amount for the random waiting?
ReaGet commented Oct 21, 2017
@hosseinGanjyar Hello! I made this delay, but I still have this error. Why?
steven1227 commented Jul 22, 2018
@ahasna can you share us a little bit experience about the waiting time?
bieladeka commented Oct 5, 2018
I have to wait about 10 hours. Did anyone find a solution?
digidecor3d commented Nov 25, 2018
ahmadfarrokh commented Dec 27, 2018
emreordukaya commented Jan 11, 2019
How did you solve. can you share. we have this error.
knocte commented Jan 15, 2019
Why a new issue?
apexkid commented Apr 9, 2020
One way to circumvent this problem is to create multiple telegram clients from different phone numbers. Then call the API in round robin fashion from each client so that requests are distributed evenly
hosseinGanjyar commented Apr 11, 2020
I have got an idea and solution. How many timesdo you call an API?
And which one of API? (name)
Please share sample code. I will help you.
ajit116 commented Apr 15, 2020
Me too, have this problem and thread.sleep can’t help.
I’m using try-catch block and in catch block, using thread.sleep(exception.TimeToWait), but with this way, application freez for second such as 200s.
No solution . 🙁
can you tel me, when u get this error ? in sendmessage method I’m try to send to 100 users successful without error.
I got ‘Getting Flood Error from telegram. Script is stopping now. Please try again after some time.’ after only 4 message and then after waiting for hours still not able to send. Any suggestion
arpanjossan46 commented Jul 2, 2020
Can u tell me how to use this . Bcoz i use another script i am getting flood error
thepasterover commented Jul 14, 2020
Has anyone found a optimisation time to avoid the PEER FLOOD ERROR?
mostafa8026 commented Dec 12, 2020
There is not such thing. It is completely on telegram algorithm that manage this time. you have to write the program for a general use, not spam 😉
Источник
Коды ошибок Telegram API
В данной статье собраны ошибки, возвращаемые API Telegram. Числовое значение аналогично статусу HTTP. Содержит информацию о типе возникшей ошибки: например, ошибка ввода данных, ошибка конфиденциальности или ошибка сервера.
303 SEE_OTHER
Запрос необходимо повторить, но направить в другой центр обработки данных.
- FILE_MIGRATE_X: файл, к которому нужно получить доступ, в настоящее время хранится в другом центре обработки данных.
- PHONE_MIGRATE_X: номер телефона, который пользователь пытается использовать для авторизации, связан с другим центром обработки данных.
- NETWORK_MIGRATE_X: исходный IP-адрес связан с другим центром обработки данных (для регистрации)
- USER_MIGRATE_X: пользователь, личность которого используется для выполнения запросов, связан с другим центром обработки данных (для регистрации)
Во всех этих случаях строковый литерал описания ошибки содержит номер центра обработки данных (вместо X), в который должен быть отправлен повторный запрос.
ОШИБКА 400, НЕВЕРНЫЙ ЗАПРОС
Запрос содержит ошибки. В случае, если запрос был создан с использованием формы и содержит данные, созданные пользователем, пользователь должен быть уведомлен о том, что данные должны быть исправлены, прежде чем запрос будет повторен.
- FIRSTNAME_INVALID: имя недействительно
- LASTNAME_INVALID: фамилия недействительна
- PHONE_NUMBER_INVALID: номер телефона недействителен
- PHONE_CODE_HASH_EMPTY: phone_code_hash отсутствует
- PHONE_CODE_EMPTY: phone_code отсутствует
- PHONE_CODE_EXPIRED: срок действия кода подтверждения истек
- API_ID_INVALID: комбинация api_id / api_hash недействительна
- PHONE_NUMBER_OCCUPIED: номер телефона уже используется
- PHONE_NUMBER_UNOCCUPIED: номер телефона еще не используется
- USERS_TOO_FEW: недостаточно пользователей (например, для создания чата)
- USERS_TOO_MUCH: превышено максимальное количество пользователей (например, для создания чата)
- TYPE_CONSTRUCTOR_INVALID: конструктор типа недействителен
- FILE_PART_INVALID: неверный номер части файла.
- FILE_PARTS_INVALID: недопустимое количество частей файла.
- FILE_PART_Х_MISSING: часть X (где X — номер) файла отсутствует в хранилище
- MD5_CHECKSUM_INVALID: контрольные суммы MD5 не совпадают
- PHOTO_INVALID_DIMENSIONS: размеры фотографии недействительны
- FIELD_NAME_INVALID: поле с именем FIELD_NAME недействительно
- FIELD_NAME_EMPTY: поле с названием FIELD_NAME отсутствует
- MSG_WAIT_FAILED: запрос, который должен быть выполнен перед обработкой текущего запроса, возвратил ошибку
- MSG_WAIT_TIMEOUT: запрос, который должен быть выполнен перед обработкой текущего запроса, еще не завершил обработку
401 ОШИБКА ДОСТУПА
Произошла попытка несанкционированного использования функций, доступных только авторизованным пользователям.
- AUTH_KEY_UNRIGN: Ключ не зарегистрирован в системе
- AUTH_KEY_INVALID: ключ недействителен
- USER_DEACTIVATED: пользователь удален / деактивирован
- SESSION_REVOKED: авторизация была аннулирована из-за того, что пользователь завершил все сеансы
- SESSION_EXPIRED: срок авторизации истек
- AUTH_KEY_PERM_EMPTY: метод недоступен для временного ключа авторизации, не привязан к постоянному
403 ЗАПРЕЩЕНО
Нарушение конфиденциальности. Например, попытка написать сообщение кому-то, кто занес текущего пользователя в черный список.
404 НЕ НАЙДЕНО
Попытка вызвать несуществующий объект, например метод.
406 NOT_ACCEPTABLE
Подобно 400 BAD_REQUEST , но приложение не должно отображать сообщения об ошибках для пользователя в пользовательском интерфейсе в результате этого ответа. Вместо этого сообщение об ошибке будет доставлено через updateServiceNotification.
420 FLOOD
Превышено максимально допустимое количество попыток вызвать данный метод с заданными входными параметрами. Например, при попытке запросить большое количество текстовых сообщений (SMS) на один и тот же номер телефона.
- FLOOD_WAIT_X: требуется ожидание X секунд (где X — число)
500 ВНУТРЕННИЙ
Произошла внутренняя ошибка сервера во время обработки запроса; например, произошел сбой при доступе к базе данных или файловому хранилищу.
Если клиент получает ошибку 500 или вы считаете, что эта ошибка не должна была возникнуть, пожалуйста, соберите как можно больше информации о запросе и ошибке и отправьте ее разработчикам.
Другие коды ошибок
Если сервер возвращает ошибку с кодом, отличным от перечисленных выше, это может рассматриваться как ошибка 500 и рассматриваться как внутренняя ошибка сервера.
Источник
Error handling
There will be errors when working with the API, and they must be correctly handled on the client.
An error is characterized by several parameters:
Numerical value similar to HTTP status. Contains information on the type of error that occurred: for example, a data input error, privacy error, or server error. This is a required parameter.
A string literal in the form of /[A-Z_0-9]+/ , which summarizes the problem. For example, AUTH_KEY_UNREGISTERED . This is an optional parameter.
A full machine-readable JSON list of RPC errors that can be returned by all methods in the API can be found here », what follows is a description of its fields:
- errors — All error messages and codes for each method (object).
- Keys: Error codes as strings (numeric strings)
- Values: All error messages for each method (object)
- Keys: Error messages (string)
- Values: An array of methods which may emit this error (array of strings)
- descriptions — Descriptions for every error mentioned in errors (and a few other errors not related to a specific method)
- Keys: Error messages
- Values: Error descriptions
- user_only — A list of methods that can only be used by users, not bots.
Error messages and error descriptions may contain printf placeholders in key positions, for now only %d is used to map durations contained in error messages to error descriptions.
There should be a way to handle errors that are returned in rpc_error constructors.
Below is a list of error codes and their meanings:
The request must be repeated, but directed to a different data center.
- FILE_MIGRATE_X: the file to be accessed is currently stored in a different data center.
- PHONE_MIGRATE_X: the phone number a user is trying to use for authorization is associated with a different data center.
- NETWORK_MIGRATE_X: the source IP address is associated with a different data center (for registration)
- USER_MIGRATE_X: the user whose identity is being used to execute queries is associated with a different data center (for registration)
In all these cases, the error description’s string literal contains the number of the data center (instead of the X) to which the repeated query must be sent. More information about redirects between data centers »
The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated.
- FIRSTNAME_INVALID: The first name is invalid
- LASTNAME_INVALID: The last name is invalid
- PHONE_NUMBER_INVALID: The phone number is invalid
- PHONE_CODE_HASH_EMPTY: phone_code_hash is missing
- PHONE_CODE_EMPTY: phone_code is missing
- PHONE_CODE_EXPIRED: The confirmation code has expired
- API_ID_INVALID: The api_id/api_hash combination is invalid
- PHONE_NUMBER_OCCUPIED: The phone number is already in use
- PHONE_NUMBER_UNOCCUPIED: The phone number is not yet being used
- USERS_TOO_FEW: Not enough users (to create a chat, for example)
- USERS_TOO_MUCH: The maximum number of users has been exceeded (to create a chat, for example)
- TYPE_CONSTRUCTOR_INVALID: The type constructor is invalid
- FILE_PART_INVALID: The file part number is invalid
- FILE_PARTS_INVALID: The number of file parts is invalid
- FILE_PART_X_MISSING: Part X (where X is a number) of the file is missing from storage
- MD5_CHECKSUM_INVALID: The MD5 checksums do not match
- PHOTO_INVALID_DIMENSIONS: The photo dimensions are invalid
- FIELD_NAME_INVALID: The field with the name FIELD_NAME is invalid
- FIELD_NAME_EMPTY: The field with the name FIELD_NAME is missing
- MSG_WAIT_FAILED: A request that must be completed before processing the current request returned an error
- MSG_WAIT_TIMEOUT: A request that must be completed before processing the current request didn’t finish processing yet
There was an unauthorized attempt to use functionality available only to authorized users.
- AUTH_KEY_UNREGISTERED: The key is not registered in the system
- AUTH_KEY_INVALID: The key is invalid
- USER_DEACTIVATED: The user has been deleted/deactivated
- SESSION_REVOKED: The authorization has been invalidated, because of the user terminating all sessions
- SESSION_EXPIRED: The authorization has expired
- AUTH_KEY_PERM_EMPTY: The method is unavailable for temporary authorization key, not bound to permanent
Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user.
An attempt to invoke a non-existent object, such as a method.
Similar to 400 BAD_REQUEST, but the app must display the error to the user a bit differently.
Do not display any visible error to the user when receiving the rpc_error constructor: instead, wait for an updateServiceNotification update, and handle it as usual.
Basically, an updateServiceNotification popup update will be emitted independently (ie NOT as an Updates constructor inside rpc_result but as a normal update) immediately after emission of a 406 rpc_error : the update will contain the actual localized error message to show to the user with a UI popup.
An exception to this is the AUTH_KEY_DUPLICATED error, which is only emitted if any of the non-media DC detects that an authorized session is sending requests in parallel from two separate TCP connections, from the same or different IP addresses.
Note that parallel connections are still allowed and actually recommended for media DCs.
Also note that by session we mean a logged-in session identified by an authorization constructor, fetchable using account.getAuthorizations, not an MTProto session.
If the client receives an AUTH_KEY_DUPLICATED error, the session is already invalidated by the server and the user must generate a new auth key and login again.
The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number.
- FLOOD_WAIT_X: A wait of X seconds is required (where X is a number)
An internal server error occurred while a request was being processed; for example, there was a disruption while accessing a database or file storage.
If a client receives a 500 error, or you believe this error should not have occurred, please collect as much information as possible about the query and error and send it to the developers.
If a server returns an error with a code other than the ones listed above, it may be considered the same as a 500 error and treated as an internal server error.
Источник
Здравствуйте! Пожалуйста помогите. Имеется код, я хочу чтобы питон рандомно из 5 вариантов текста ( варианты которых я должен буду ввести )выбирал 1 после каждого действия, но чтобы не полетела программа. Заранее спасибо.
P.S Ввод текста начинается с 64 строчки
#!/bin/env python3 from telethon.sync import TelegramClient from telethon.tl.types import InputPeerUser from telethon.errors.rpcerrorlist import PeerFloodError import configparser import os, sys import csv import random import time re="33[1;31m" gr="33[1;32m" cy="33[1;36m" SLEEP_TIME = 30 class main(): def banner(): print(f""" {re}╔╦╗{cy}┌─┐┌─┐┌─┐┌─┐┬─┐{re}╔═╗ {re} ║ {cy}├─┐├┤ ├─┘├─┤├┬┘{re}╚═╗ {re} ╩ {cy}└─┘└─┘┴ ┴ ┴┴└─{re}╚═╝ by frozenSQD """) def send_sms(): try: cpass = configparser.RawConfigParser() cpass.read('config.data') api_id = cpass['cred']['id'] api_hash = cpass['cred']['hash'] phone = cpass['cred']['phone'] except KeyError: os.system('clear') main.banner() print(re+"[!] run python3 setup.py first !!n") sys.exit(1) client = TelegramClient(phone, api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) os.system('clear') main.banner() client.sign_in(phone, input(gr+'[+] Enter the code: '+re)) os.system('clear') main.banner() input_file = sys.argv[1] users = [] with open(input_file, encoding='UTF-8') as f: rows = csv.reader(f,delimiter=",",lineterminator="n") next(rows, None) for row in rows: user = {} user['username'] = row[0] user['id'] = int(row[1]) user['access_hash'] = int(row[2]) user['name'] = row[3] users.append(user) print(gr+"[1] send sms by user IDn[2] send sms by username ") mode = int(input(gr+"Input : "+re)) message = input(gr+"[+] Enter Your Message : "+re) for user in users: if mode == 2: if user['username'] == "": continue receiver = client.get_input_entity(user['username']) elif mode == 1: receiver = InputPeerUser(user['id'],user['access_hash']) else: print(re+"[!] Invalid Mode. Exiting.") client.disconnect() sys.exit() try: print(gr+"[+] Sending Message to:", user['name']) client.send_message(receiver, message.format(user['name'])) print(gr+"[+] Waiting {} seconds".format(SLEEP_TIME)) time.sleep(20) except PeerFloodError: print(re+"[!] Getting Flood Error from telegram. n[!] Script is stopping now. n[!] Please try again after some time.") client.disconnect() sys.exit() except Exception as e: print(re+"[!] Error:", e) print(re+"[!] Trying to continue...") continue client.disconnect() print("Done. Message sent to all users.") main.send_sms()
Отредактировано Frozen192 (Ноя. 19, 2021 14:44:48)