Mass dm bot (Instagram)

Bot which use instagrapi library to send large amount of direct messages in Instagram work with proxy`s Is used Python as programming language is written in Tkinter library for gui interface also use threading to send with 3 accounts at a time.
 avatar
unknown
plain_text
4 years ago
17 kB
5
Indexable
from instagrapi import Client
from instagrapi.exceptions import LoginRequired, UnknownError, FeedbackRequired, UserNotFound, ClientError, ClientConnectionError, ClientNotFoundError
import time
import random, os, sys
from datetime import date
import tkinter as tk
from tkinter import *
from PIL import Image, ImageTk
from tkinter import filedialog
import emoji, threading, sqlite3

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.title('Instagram Bot')
        self.geometry("500x600")
        self.image = None
        # Set background image
        self.canvas = Canvas(self._frame,width=200,height=200)
        self.image = ImageTk.PhotoImage(Image.open('ngineX.png'))
        self.canvas.create_image(0,0,anchor=NW,image=self.image)
        self.canvas.pack()
        self.image1 = None
        self.canvas1 = Canvas(self._frame,width=200,height=200)
        self.image1 = ImageTk.PhotoImage(Image.open('41KSu1weSuL.jpg'))
        self.canvas1.create_image(0,0,anchor=NW,image=self.image1)
        self.canvas1.pack()
        self.switch_frame(StartPage)
        self.amount = None
        self.name = None
        self.url = None
        self.time = None
        self.user = None
        self.amout_dm = None
        self.proxy_count = None
        self.requsets_time = None
        self.amount_dm_total = None
        
    def switch_frame(self, frame_class):
        """Destroys current frame and replaces it with a new one."""
        new_frame = frame_class(self)
        if self._frame is not None:
            self.canvas1.destroy()
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()




class StartPage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
    
        tk.Label(self, text="code by Mike Hadzhiev").pack(side="top", fill="x", pady=10)

        tk.Button(self, text="Login", command=lambda: master.switch_frame(PageOne)).pack()





class PageOne(tk.Frame):
	def __init__(self, master):
		tk.Frame.__init__(self, master)
		tk.Label(self, text="Welcome to Instagram Bot \n Plese choice a option").pack(side="top", fill="x", pady=10)
		tk.Button(self, text='Send dm from user list', command=lambda: master.switch_frame(Dm_likers)).pack()
		tk.Button(self, text='Export list of users followers', command=lambda: master.switch_frame(Export_users)).pack()
		tk.Button(self, text='Export settings', command=lambda: master.switch_frame(Export_setting)).pack()

class Dm_likers(tk.Frame):
	def __init__(self, master):
		tk.Frame.__init__(self, master)
		self.file_lbl1 = tk.Label(self, text='Load file with users')
		self.file_lbl1.pack(side='top',fill='x',pady=10)
		tk.Button(self, text='Browse files', command=self.browseFiles_hstg1).pack()
		
		self.file_lbl2 = tk.Label(self, text='Enter number of dm per account')
		self.file_lbl2.pack(side='top',fill='x',pady=10)
		self.amout_dm = tk.Entry(self)
		self.amout_dm.pack()

		self.file_lbl3 = tk.Label(self, text='Enter number of accounts per proxy')
		self.file_lbl3.pack(side='top',fill='x',pady=10)
		self.proxy_count = tk.Entry(self)
		self.proxy_count.pack()

		self.file_lbl4 = tk.Label(self, text='Enter seconds for each meesage request')
		self.file_lbl4.pack(side='top',fill='x',pady=10)
		self.requsets_time = tk.Entry(self)
		self.requsets_time.pack()

		self.file_lbl5 = tk.Label(self, text='Enter total amount of messages you want to send')
		self.file_lbl5.pack(side='top',fill='x',pady=10)
		self.amount_dm_total = tk.Entry(self)
		self.amount_dm_total.pack()

		tk.Button(self,text='Start Bot', command=self.go).pack()
		tk.Button(self, text='Back', command=lambda: master.switch_frame(PageOne)).pack()
	

	def browseFiles_hstg1(self): 
	    filename = filedialog.askopenfilename(initialdir = "/", 
	                                      title = "Select a File", 
	                                      filetypes = (("Text files", 
	                                                    "*.txt*"), 
	                                                   ("all files", 
	                                                    "*.*"))) 
	    # Change label contents 
	    self.file_lbl1.configure(text = filename)
    
   

	def go(self):
		self.save_credentials()
		self.start_location()


	def save_credentials(self):
		self.master.amout_dm = self.amout_dm.get()
		self.amout_dm1 = int(self.master.amout_dm) 
		self.master.proxy_count = self.proxy_count.get()
		self.proxy_count1 = int(self.master.proxy_count)
		self.master.requsets_time = self.requsets_time.get()
		self.requsets_time1 = int(self.master.requsets_time)
		self.master.amount_dm_total = self.amount_dm_total.get()
		self.amount_dm_total1 = int(self.master.amount_dm_total)

	def start_location(self):
		username_lst = list()
		media_id_hash = list()
		user_id_lst = list()
		sys.tracebacklimit=0

		try:
			conn = sqlite3.connect('users_limit_database.db', check_same_thread=False)
			cursor = conn.cursor()
			print("Opened database successfully")
		except:
			print('Can`t open database')

		try:
			cursor.execute('''CREATE TABLE  USER_COUNT (USERNAME TEXT UNIQUE , AMOUNT_MESSAGES INT );''')
			print ("Table created successfully")
		except:
			pass


		with open('accounts.txt','r') as file:
			data_accounts = [line.strip() for line in file]

		with open('proxyipv4.txt','r') as file:
			data_proxy = [line.strip() for line in file]

		with open(self.file_lbl1.cget('text'), 'r') as file:
			data_users = [line.strip() for line in file]

		with open('messages.txt', 'r') as file:
			data_message = [line.strip() for line in file]
		
		# with open('old_users.txt', 'r') as file:
		# 	old_users = [line.strip() for line in file]

		newcl = 'cl'
		cl_list = list()
		cl_list_final = list()
		account_name = list()

		for each in range(int(len(data_accounts) / 2)):
			newcl = newcl + str(each)
			cl_list.append(newcl)
			newcl = 'cl'
		
		count = 0
		n = 1
		x = 0
		global count_account
		count_account = 0
		proxy = 'https://' + data_proxy[0]

		users_limit = cursor.execute("SELECT USERNAME FROM USER_COUNT WHERE AMOUNT_MESSAGES >= 30")
		#print(type(users_limit), users_limit)
		data_accounts_limit = list()
		
		dadta = cursor.fetchall()
		#print(dadta)

		for each_t in dadta:
			print(each, type(each))
			for each in each_t:
				print(each, type(each))
				data_accounts_limit.append(each)

		for each_ac, each_p in zip(data_accounts[0::2], data_accounts[1::2]):
			for each_a in data_accounts_limit:
				if each_ac == each_a:
					data_accounts_limit.append(each_p)

		#print(data_accounts_limit)
		data_accounts = [x for x in data_accounts if x not in data_accounts_limit]

		for each_usr, each_pass, cl_name in zip(data_accounts[0::2], data_accounts[1::2], cl_list):
			if count == self.proxy_count1:
					proxy = 'https://' + data_proxy[n]
					count = 0
					n += 1
			else:
				pass
		
			ACCOUNT_USERNAME = each_usr
			ACCOUNT_PASSWORD = each_pass
			try:
				cl_name = Client()
				cl_name.request_timeout = self.requsets_time1
				print(proxy)
				cl_name.set_proxy(proxy)	
				cl_name.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
				cl_list_final.append(cl_name)
				account_name.append(ACCOUNT_USERNAME)
				print('Login with ', ACCOUNT_USERNAME)
				count += 1
				with open('good_accounts.txt', 'a+') as file:
					file.write(ACCOUNT_USERNAME + '\n')
				count_account += 1
				try:	
					cursor.execute("INSERT INTO USER_COUNT VALUES (?, ?);", (ACCOUNT_USERNAME, 0))
					conn.commit()
				except:
					pass

				if count_account == self.amount_dm_total1 / self.amout_dm1:
					break
			except Exception as e:
				print(str(e))
				proxy = 'https://' + data_proxy[n]
				n += 1
				print('Can`t login with', ACCOUNT_USERNAME)
				with open('report_bad_accounts.txt', 'a+') as file:
					file.write(each_usr + '\n')

	

		msg = random.choice(data_message)
			
		with open('old_users.txt', 'r') as file:
			old_users = [line.strip() for line in file]
				
		data_users = [x for x in data_users if x not in old_users]
		# global count_messages_send
		# count_messages_send = 0


		def firstOne(data_users, cl_list, acc_namee):
			global count_messages_send
			count_messages_send = 0
			i = count_account / 3
			j = int(i)
			#print(j)
			msg = random.choice(data_message)
			for each_cl, acc_name in zip(cl_list_final[:j], account_name[:j]):
				count1 = 0
				for each_usr in data_users:
					with open('old_users.txt', 'a+') as file:
						file.write(each_usr + '\n')
					try:
						try:
							user_Ids = each_cl.user_id_from_username(each_usr)
						except:
							continue
						each_cl.direct_send(msg ,[user_Ids])
						print('Direct message send: ', msg, ' to user', each_usr, ' from username ', acc_name)
						count1 += 1
						cursor.execute("UPDATE USER_COUNT SET AMOUNT_MESSAGES =  (?)  WHERE USERNAME = (?);", (count1, acc_name))
						conn.commit()
					#	today = date.today()
						count_messages_send += 1
						# d1 = today.strftime("%d/%m/%Y")
						# with open('report_mid.txt', 'w') as file:
						# 	file.write(str(d1) + ' messages send: ' + str(count_messages_send) + '\n')

						old_users.append(each_usr)
						if count1 == self.amout_dm1:
							break					
									
					except Exception as e:
						if 'We limit how often you can do certain things on Instagram' in str(e):
							break
						else:			
							with open('old_users.txt', 'a+') as file:
								file.write(each_usr + '\n')
						
						print(str(e))
						break
					except Exception as e:
						print(str(e))
						break

		def firstSecond(data_users, cl_list, acc_namee):
			global count_messages_send1
			count_messages_send1 = 0
			i = count_account / 3
			j = int(i)
			msg = random.choice(data_message)
			for each_cl, acc_name in zip(cl_list_final[j:j+j], account_name[j:j+j]):
				count1 = 0

				for each_usr in data_users:
					try:
						with open('old_users.txt', 'a+') as file:
							file.write(each_usr + '\n')
						try:
							user_Ids = each_cl.user_id_from_username(each_usr)
						except:
							continue
						each_cl.direct_send(msg ,[user_Ids])
						print('Direct message send: ', msg, ' to user', each_usr, ' from username ', acc_name)
						count1 += 1
						cursor.execute("UPDATE USER_COUNT SET AMOUNT_MESSAGES =  (?)  WHERE USERNAME = (?);", (count1, acc_name))						#today = date.today()
						conn.commit()
						count_messages_send1 += 1
						# d1 = today.strftime("%d/%m/%Y")
						# count_messages_send2 = count_messages_send1 + count_messages_send
						# with open('report_mid.txt', 'w') as file:
						# 	file.write(str(d1) + ' messages send: ' + str(count_messages_send2) + '\n')

						old_users.append(each_usr)
						if count1 == self.amout_dm1:
							break					
									
					except Exception as e:
						if 'We limit how often you can do certain things on Instagram' in str(e):
							break
						else:			
							with open('old_users.txt', 'a+') as file:
								file.write(each_usr + '\n')
						
						print(str(e))
						break
					except Exception as e:
						print(str(e))
						break

		def firstThird(data_users, cl_list, acc_namee):
			global count_messages_send2
			count_messages_send2 = 0
			i = count_account / 3
			j = int(i)
			msg = random.choice(data_message)
			for each_cl, acc_name in zip(cl_list_final[j+j:], account_name[j+j:]):
				count1 = 0
				for each_usr in data_users:
					try:
						with open('old_users.txt', 'a+') as file:
							file.write(each_usr + '\n')
						try:
							user_Ids = each_cl.user_id_from_username(each_usr)
						except:
							continue
						each_cl.direct_send(msg ,[user_Ids])
						print('Direct message send: ', msg, ' to user', each_usr, ' from username ', acc_name)
						count1 += 1
						
						cursor.execute("UPDATE USER_COUNT SET AMOUNT_MESSAGES =  (?)  WHERE USERNAME = (?);", (count1, acc_name))
						conn.commit()
						count_messages_send2 += 1
						today = date.today()
						d1 = today.strftime("%d/%m/%Y")
						total = count_messages_send + count_messages_send1 + count_messages_send2
						with open('report_mid.txt', 'w') as file:
							file.write(str(d1) + ' messages send: ' + str(total) + '\n')

						# #count_messages_send4 = count_messages_send3 + count_messages_send2
						# d1 = today.strftime("%d/%m/%Y")
						# with open('report_mid.txt', 'w') as file:
						# 	file.write(str(d1) + ' messages send: ' + str(count_messages_send4) + '\n')

						old_users.append(each_usr)
						if count1 == self.amout_dm1:
							break					
									
					except Exception as e:
						if 'We limit how often you can do certain things on Instagram' in str(e):
							break
						else:			
							with open('old_users.txt', 'a+') as file:
								file.write(each_usr + '\n')
						
						print(str(e))
						break
					except Exception as e:
						print(str(e))
						break

		user_to = self.amount_dm_total1 / 3
		q = int(user_to)
		#print(q)
		t1 = threading.Thread(target=firstOne, args=(data_users[:q], cl_list_final, account_name,))
		t2 = threading.Thread(target=firstSecond, args=(data_users[q:q+q], cl_list_final, account_name,))
		t3 = threading.Thread(target=firstThird, args=(data_users[q+q:q+q+q], cl_list_final, account_name,))

		t1.start()
		t2.start()
		t3.start()

		t1.join()
		t2.join()
		t3.join()

		today = date.today()
		d1 = today.strftime("%d/%m/%Y")
		total = count_messages_send + count_messages_send1 + count_messages_send2
		with open('report.txt', 'a+') as file:
			file.write(str(d1) + ' messages send: ' + str(total) + '\n')

		# with open('report.txt', 'a+') as file:
		# 	file.write(str(d1) + ' messages send: ' + str(count_messages_send) + '\n')

class Export_users(tk.Frame):
	def  __init__(self, master):
		tk.Frame.__init__(self, master)
		self.hastag_lbl = tk.Label(self, text='Choice name of the file')
		self.hastag_lbl.pack(side='top',fill='x',pady=10)
		self.name = tk.Entry(self)
		self.name.pack()
		self.hastag_lbl1 = tk.Label(self, text='Choice username to extract followers from')
		self.hastag_lbl1.pack(side='top',fill='x',pady=10)
		self.user = tk.Entry(self)
		self.user.pack()
		self.hastag_lbl2 = tk.Label(self, text='Enter amount of followers or 0 for all')
		self.hastag_lbl2.pack(side='top',fill='x',pady=10)
		self.amount = tk.Entry(self)
		self.amount.pack()
		self.file_lbl = tk.Label(self, text='Load settings file:')
		self.file_lbl.pack(side='top',fill='x',pady=10)
		tk.Button(self, text='Browse files', command=self.browseFiles_interact).pack()

		tk.Button(self, text='Start Bot', command=self.go).pack()
		tk.Button(self, text='Back', command=lambda: master.switch_frame(PageOne)).pack()
	
	def browseFiles_interact(self): 
	    filename = filedialog.askopenfilename(initialdir = "/", 
	                                          title = "Select a File", 
	                                          filetypes = (("Text files", 
	                                                        "*.txt*"), 
	                                                       ("all files", 
	                                                        "*.*"))) 
	    # Change label contents 
	    self.file_lbl.configure(text = filename)


    
	def go(self):
	    self.save_credentials()
	    self.start_hashtag()


	def save_credentials(self):
		self.master.name = self.name.get()
		self.name1 = str(self.master.name)
		self.master.user = self.user.get()
		self.user1 = str(self.master.user)
		self.master.amount = self.amount.get()
		self.amount1 = int(self.master.amount)


	def start_hashtag(self): 
		with open('account.txt', 'r') as file:
			ACCOUNT_USERNAME = file.readline()
			ACCOUNT_PASSWORD = file.readline()

		cl = Client()
		if 'Load settings file:' not in self.file_lbl.cget('text'):
			cl.load_settings(self.file_lbl.cget('text'))
		else:
			pass
		cl.request_timeout = 15
		cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
		print('Bot login with username: @' + ACCOUNT_USERNAME)
		user_Id = cl.user_id_from_username(self.user1)
		user_followers = cl.user_followers(user_Id, amount=self.amount1)
		keys = user_followers.keys()
		for each in keys:
			username = user_followers[each].username
			with open(self.name1, 'a+') as file:
				file.write(username + '\n')



class Export_setting(tk.Frame):
	def  __init__(self, master):
		tk.Frame.__init__(self, master)
		self.hastag_lbl = tk.Label(self, text='Choice name of the file')
		self.hastag_lbl.pack(side='top',fill='x',pady=10)
		self.name = tk.Entry(self)
		self.name.pack()

		tk.Button(self, text='Start Bot', command=self.go).pack()
		tk.Button(self, text='Back', command=lambda: master.switch_frame(PageOne)).pack()

    
	def go(self):
	    self.save_credentials()
	    self.start_hashtag()


	def save_credentials(self):
		self.master.name = self.name.get()
		self.name1 = str(self.master.name)

	def start_hashtag(self): 
		with open('account.txt', 'r') as file:
			ACCOUNT_USERNAME = file.readline()
			ACCOUNT_PASSWORD = file.readline()
			file.close()
		location_file = os.getcwd() + '/' + self.name1
		cl = Client()
		cl.request_timeout = random.choice(range(15,25))
		cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD)
		print('Bot login with username: @' + ACCOUNT_USERNAME)
		cl.dump_settings(location_file)





if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()
Editor is loading...