Skip to content

Commit

Permalink
fix deleting
Browse files Browse the repository at this point in the history
  • Loading branch information
Pycomet committed Oct 22, 2020
1 parent 970af6e commit ceef3f2
Show file tree
Hide file tree
Showing 4 changed files with 172 additions and 26 deletions.
Binary file modified __pycache__/config.cpython-36.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion app.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ runtime: python38
env_variables:
API_ID: "683428"
API_HASH: "967b28d111f82b906b6f28da1ff04411"
TOKEN: "1094295882:AAEF0PwOQKL88K6L5zslnpxKxWCGnfd0s3Q"
TOKEN: "1349826643:AAG4G6pwlkaey8BozH9CHakUZSge2dvNJAA"
DB_USER: "hunters_user"
DB_PASS: "hunters"
WEBHOOK_URL: "https://weblulue-app.df.r.appspot.com/"
3 changes: 2 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from pymongo import MongoClient
from telethon import TelegramClient, events, sync
import telebot
from telebot import types
import asyncio
from time import sleep
from telethon.tl.functions.channels import JoinChannelRequest
Expand All @@ -19,7 +20,7 @@
from apscheduler.schedulers.background import BackgroundScheduler
import requests

DEBUG = False
DEBUG = True

scheduler = BackgroundScheduler()
scheduler.start()
Expand Down
193 changes: 169 additions & 24 deletions handlers/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

customMsg = ''
targetGrp = ''
questionId = 0

imageAttached = False
fileName = ""
Expand All @@ -24,49 +25,122 @@
registeredusers = [n[0] for n in idlist]



sent = 0
views = 0
clicks = 0
campaignId = ''
starter_msg = ''
error_msg = ''


@bot.message_handler(commands=['start'])
def targetGroup(msg):
"""Request The Target Group From User"""
global user

global user, starter_msg, error_msg
user = msg.from_user

bot.reply_to(msg, f"Hello {user.username}")
if error_msg != '':
bot.delete_message(error_msg.chat.id, error_msg.message_id)

markup = types.InlineKeyboardMarkup(row_width=2)
btn1 = types.InlineKeyboardButton(
text= 'Start New Campaign 🎤',
callback_data= 'new'
)
markup.add(btn1)

starter_msg = bot.reply_to(
msg,
f"""
Hello {user.username}!
Welcome to <a href="https://t.me/tg_Adbot"><b>The Ultimate Ads Bot</b></a>, helping business owners reach out to more potential customers worldwide through telegram.
You can <b>get started</b> by creating your first campaign 🎟 and see your audience on your content grow from zero to hero
""",
parse_mode = "html",
reply_markup = markup,
disable_web_page_preview = True
)

return starter_msg

# Ask Request
question = bot.send_message(user.id, "Please reply with a valid telegram group link..")

bot.register_next_step_handler(question, joinGroup)
# Callback Handlers
@bot.callback_query_handler(func=lambda call: True)
def callback_answer(call):
"""
Button Response
"""
global questionId

bot.delete_message(starter_msg.chat.id, starter_msg.message_id)

if call.data == "new":
# Ask Request
question = bot.send_message(
user.id,
"Paste a valid and active telegram group link to be used for audience referencing...",
reply_markup=types.ForceReply(selective=True)
)
questionId = question.message_id

bot.register_next_step_handler(question, joinGroup)

elif call.data == "old":

print("Not yet fixed!")

else:
pass

return questionId



def joinGroup(msg):
"""Join The Target Group And Request Message From User"""

global targetGrp
global admins
global targetGrp, admins, questionId, error_msg

# delete incoming
bot.delete_message(msg.chat.id, questionId)

try:
targetGrp = msg.text

# Extracting Admin Information For the target group
[admins.append(admin.user.id) for admin in bot.get_chat_administrators(targetGrp)]


# Ask Request
question = bot.send_message(user.id, "Paste your custom message content here --")
question = bot.send_message(
user.id,
"Paste in your advert content to be shared on your campaign...",
reply_markup=types.ForceReply(selective=True)
)
questionId = question.message_id

bot.register_next_step_handler(question, send)

except Exception as e:

bot.send_message(user.id, f"Invalid Request! - {e}")
error_msg = bot.send_message(user.id, f"Invalid Request! Try All Over Again 😟")
targetGroup(msg)

# import pdb; pdb.set_trace()
bot.delete_message(msg.chat.id, msg.message_id)
return questionId, targetGrp, admins, error_msg



def send(msg):
"""Save and start sending message"""

global customMsg
global imageAttached
global customMsg, imageAttached, sent, views, clicks, campaignId

# delete incoming
bot.delete_message(msg.chat.id, questionId)

if msg.content_type != 'text':
customMsg = msg.caption
Expand All @@ -76,6 +150,26 @@ def send(msg):
customMsg = msg.text
imageAttached = False

# CAMPAIGN MESSAGE
message = bot.send_message(
user.id,
text = f"""
🏁 <b>CAMPAIGN STATUS</b>
Your campaign has just been created and your content is going out....
Target Audience -> {targetGrp}
Administrators excluded -> {len(admins)}
<b>Sent</b> -> {sent}
<b>Views</b> -> {views}
<b>Clicks</b> -> {clicks}
""",
parse_mode= "html",
)
campaignId = message.message_id

bot.delete_message(msg.chat.id, msg.message_id)

for session, session_user in zip(SESSIONS, SESSION_USERS):

loop = asyncio.new_event_loop()
Expand All @@ -99,6 +193,22 @@ def send(msg):
time = datetime.now() + timedelta(minutes=2)
scheduler.add_job(delete_message, trigger='date', run_date=time, id=f'by_{session_user}', args=(msg_ids, client, messages))

bot.edit_message_text(
chat_id = user.id,
message_id = campaignId,
text = f"""
🏴 <b>CAMPAIGN CLOSED</b>
---------------------------
Target Audience -> {targetGrp}
Administrators excluded -> {len(admins)}
<b>Sent</b> -> {sent}
<b>Views</b> -> {views}
<b>Clicks</b> -> {clicks}
""",
parse_mode = "html",
)



def download_attachment(img):
Expand All @@ -120,22 +230,36 @@ def download_attachment(img):
async def sendMessage(id, session_user, client):
"""Send The Custom Message To A Target Group"""

global index
global warning
bot.send_message(id, f"{session_user} Sending Messages.....")
global index, warning, sent, views, clicks

bot.edit_message_text(
chat_id = id,
message_id = campaignId,
text = f"""
🏳️ <b>CAMPAIGN ACTIVE</b>
Your campaign is live, active with <b>{session_user}</b>
<b>Sent</b> -> {sent}
<b>Views</b> -> {views}
<b>Clicks</b> -> {clicks}
""",
parse_mode = "html",
)

try:
group = await client.get_entity(targetGrp)
# Join Group
await client(JoinChannelRequest(group))

bot.send_message(id, f'{session_user} Joined {group.title} Group Successfully!')
try:
# Join Group
await client(JoinChannelRequest(group))
except Exception as e:
pass

## Get All the users from the target group
members = await client.get_participants(group)

## Send message to the members individually
for user in members[index::]:
for user in members[index:5]:
if user.bot == False:
if user.id not in admins and str(user.id) not in registeredusers:

Expand Down Expand Up @@ -168,14 +292,13 @@ async def sendMessage(id, session_user, client):
}
result = message_db.messages.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))

bot.send_message(id, f"Sent to {user.username}")
sent += 1

except Exception as e:
warning += 1

if warning >= 5:
bot.send_message(id, f"Failed to send anymore message with {user.username}")
bot.send_message(id, f"Failed to send anymore message with {session_user}")
warning = 0
return None
else:
Expand All @@ -184,10 +307,31 @@ async def sendMessage(id, session_user, client):

#Setting the state
index += 1
bot.edit_message_text(
chat_id = id,
message_id = campaignId,
text = f"""
🏳️ <b>CAMPAIGN ACTIVE</b>
---------------------------
<b>Sent</b> -> {sent}
<b>Views</b> -> {views}
<b>Clicks</b> -> {clicks}
""",
parse_mode = "html",
)

except Exception as e:
print(e)
bot.send_message(id, "Error in your input! Try again with requested valid data")
bot.edit_message_text(
chat_id = id,
message_id = campaignId,
text = """
🚩 <b>CAMPAGIN INACTIVE</b>
---------------------------
Error in your input! Please verify the group link provided and try creating the campaign again
""",
parse_mode = "html",
)


def delete(msg_ids, client, messages):
Expand All @@ -201,4 +345,5 @@ async def deleteMessages(ids, client, messages):
await client.delete_messages(entity=None, message_ids=list(ids))

[message_db.messages.delete_one(payload) for payload in messages]

return await client.disconnect()

0 comments on commit ceef3f2

Please sign in to comment.