Skip to content

Instantly share code, notes, and snippets.

@Nilpo
Created July 30, 2017 01:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nilpo/28290fe7dfb84d34765864b10be44a90 to your computer and use it in GitHub Desktop.
Save Nilpo/28290fe7dfb84d34765864b10be44a90 to your computer and use it in GitHub Desktop.
from line import LineClient, LineGroup, LineContact, LineMessage
import os
import sys
import re
import ast
from curve.ttypes import OperationType, TalkException
try:
# client5 = LineClient("teambarrsackbot5@gmail.com", "321321Ab", authToken="EiLW77LqJc7usR6vB5z9.7x9TsSw19TOlLNYRF2HOUq.sCuQ9zBZ90djqjN0dkBubuPcT2WDi5mG5razGdrcrgI=", com_name="Aero5", is_mac=False)
# client5 = LineClient(os.environ['LINE_ULTRON_LOGIN'], os.environ['LINE_ULTRON_PASS'], com_name="Aero5", is_mac=False)
# client5 = LineClient("teambarrsackbot5@gmail.com", "321321Ab", com_name="Aero5", is_mac=False)
# client5 = LineClient(authToken=client5.authToken, com_name="Aero5", is_mac=False)
client5 = LineClient(os.environ['LINE_LOGIN_TESTBOT1'], os.environ['LINE_PASS_TESTBOT1'], is_mac=False)
client5 = LineClient(authToken=client5.authToken, com_name=os.uname()[1], is_mac=False)
print
"Login successful"
print "Login successful"
except TalkException as e:
print "Login Failed:", e.reason
def bannedfunc():
groups = client5._getGroups(client5._getGroupIdsJoined())
for group in groups:
members = group.members
for member in members:
if member.mid in banned:
client5._kickoutFromGroup(group.id, [member.mid])
# os.chdir("./txt files")
#get bots
with open("txt files/bots.txt","r") as f:
bots = f.read().splitlines()
#get owners
with open("txt files/owners.txt","r") as f:
owners = f.read().splitlines()
#get admins
with open("txt files/admins.txt","r") as f:
admins = f.read().splitlines()
#get banned users
with open("txt files/banned.txt","r") as f:
banned = f.read().splitlines()
with open("txt files/bannedNames.txt","r") as f:
bannedNames = f.read().splitlines()
#get muted users
with open("txt files/muted.txt","r") as f:
mutedList = f.read().splitlines()
with open("txt files/mutedNames.txt","r") as f:
mutedNames = f.read().splitlines()
#variables
staff = owners + admins
botName = "testbot "
addOwner = False
delOwner = False
groupcastSender = ""
ownerSender = ""
addAdmin = False
delAdmin = False
staffSender = ""
lurking = False
muteSender = ""
changestatusmessageSender = ""
changebotnameSender = ""
unmuteSender = ""
addbotSender = ""
usersThatRead = []
lurkGroup = ""
banSender = ""
banning = False
delstaffSender = ""
delbotSender = ""
unbanSender = ""
unbanning = False
copySender = ""
cancelall = False
welcomeSender = ""
OT = OperationType
while True:
for operation in client5.longPoll():
if operation.type == OT.END_OF_OPERATION:
pass
if operation.type == OT.RECEIVE_MESSAGE:
#receive message
message = LineMessage(client5, operation.message)
raw_sender = operation.message._from
raw_receiver = operation.message.to
sender = client5.getContactOrRoomOrGroupById(raw_sender)
receiver = client5.getContactOrRoomOrGroupById(raw_receiver)
# If sender is not found, check member list of group chat sent to
if sender is None:
try:
for m in receiver.members:
if m.id == raw_sender:
sender = m
break
except (AttributeError, TypeError):
pass
# If sender is not found, check member list of room chat sent to
if sender is None:
try:
for m in receiver.contacts:
if m.id == raw_sender:
sender = m
break
except (AttributeError, TypeError):
pass
if sender is None or receiver is None:
client5.refreshGroups()
client5.refreshContacts()
client5.refreshActiveRooms()
sender = client5.getContactOrRoomOrGroupById(raw_sender)
receiver = client5.getContactOrRoomOrGroupById(raw_receiver)
if sender is None or receiver is None:
contacts = client5._getContacts([raw_sender, raw_receiver])
if contacts:
if len(contacts) == 2:
sender = LineContact(client5, contacts[0])
receiver = LineContact(client5, contacts[1])
check = True
if sender != None:
if sender.id in mutedList:
try:
receiver.sendMessage("Silence...")
client5._kickoutFromGroup(receiver.id,[sender.id])
except:
print "an error occured while trying to kick muted user"
else:
sid = sender.id
else:
sid = ""
if sid in bots:
check = False
if receiver == None:
check = False
#IF RECEIVED CONTACT
if message.contentType == 13:
try:
user = message.contentMetadata
userValues = user.values()
contactId = userValues[1]
contactName = userValues[0]
except:
break
if sid == addbotSender:
addbotSender = ""
if contactId in bots:
receiver.sendMessage("This is already a bot")
else:
try:
bots.append(contactId)
content = "\n".join(bots)
client5._findAndAddContactsByMid(contactId)
file = open("txt files/bots.txt","w")
file.write(content)
file.close()
except:
receiver.sendMessage("An error occured")
if sid == copySender:
copySender = ""
receiver.sendMessage("Copying "+contactName + "'s profile..")
toCopy = client5._findAndAddContactsByMid(contactId)
#imgPath = "http://dl.profile.line.naver.jp" + (toCopy[contactId].picturePath)
statusMessage = (toCopy[contactId].statusMessage)
try:
#change name
client5._client_out.updateProfileAttribute(0,2,contactName)
#change status message
client5._client_out.updateProfileAttribute(0,16,statusMessage)
#change profile picture
#client5._client_out.updateProfileAttribute(0,8,r)
#change callname
botName = contactName.lower() + " "
except:
receiver.sendMessage("Failed to copy "+contactName)
if addOwner:
if sid == ownerSender:
ownerSender = ""
if contactId in owners:
receiver.sendMessage(contactName + " has already been added as owner")
else:
owners.append(contactId)
staff = owners + admins
receiver.sendMessage(contactName + " is now an owner")
try:
file = open("txt files/owners.txt","w")
file.write("\n".join(owners))
file.close()
addOwner = False
except:
addOwner = False
print "Adding owner failed"
if addAdmin:
if sid == staffSender:
staffSender = ""
if contactId in admins:
receiver.sendMessage(contactName + " has already been added as admin")
else:
admins.append(contactId)
staff = owners + admins
receiver.sendMessage(contactName + " is now an admin")
try:
# file = open("admins.txt","r")
# content = file.read()
# file.close()
file = open("txt files/admins.txt","w")
file.write("\n".join(admins))
file.close()
addAdmin = False
except:
addAdmin = False
print "Adding admin failed"
if delAdmin:
if sid == delstaffSender:
delstaffSender = ""
if contactId in admins:
admins.remove(contactId)
staff = owners + admins
receiver.sendMessage(contactName + " is no longer an admin")
try:
file = open("txt files/admins.txt","w")
file.write("\n".join(admins))
file.close()
delAdmin = False
except:
delAdmin = False
print "removing admin failed"
else:
receiver.sendMessage("Could not find " +contactName +" in admins")
if delOwner:
if sid == delstaffSender:
delstaffSender = ""
if contactId in owners:
owners.remove(contactId)
staff = owners + admins
receiver.sendMessage(contactName + " is no longer an owner")
try:
file = open("txt files/owners.txt","w")
file.write("\n".join(owners))
file.close()
delOwner = False
except:
delOwner = False
print "removing admin failed"
else:
receiver.sendMessage("Could not find " +contactName +" in owners")
if delBot:
if sid == delbotSender:
delbotSender = ""
if contactId in bots:
bots.remove(contactId)
receiver.sendMessage(contactName + " is no longer a bot")
try:
file = open("txt files/bots.txt","w")
file.write("\n".join(bots))
file.close()
delBot = False
except:
delBot = False
print "removing bot failed"
else:
receiver.sendMessage("Could not find " +contactName +" in bots")
if banning:
if sid == banSender:
banSender = ""
if contactId in banned:
receiver.sendMessage(contactName + " has already been banned")
banning = False
elif contactId in bots or contactId in admins or contactId in owners:
receiver.sendMessage("Unable to ban staff or friendly bots")
banning = False
else:
banned.append(contactId)
bannedfunc()
bannedNames.append(contactName)
receiver.sendMessage(contactName + " has been banned")
try:
file = open("txt files/banned.txt","w")
file.write("\n".join(banned))
file.close()
file = open("txt files/bannedNames.txt","w")
file.write("\n".join(bannedNames))
file.close()
groupMembers = receiver.members
memberIds = [o.id for o in groupMembers]
if contactId in memberIds:
client5._kickoutFromGroup(receiver.id,[contactId])
banning = False
except:
banning = False
print "Banning user failed"
if unbanning:
if sid == unbanSender:
unbanSender = ""
if contactId in banned:
index = banned.index(contactId)
banned.pop(index)
bannedNames.pop(index)
receiver.sendMessage(contactName + " has been unbanned")
try:
file = open("txt files/banned.txt","w")
file.write("\n".join(banned))
file.close()
file = open("txt files/bannedNames.txt","w")
file.write("\n".join(bannedNames))
file.close()
unbanning = False
except:
unbanning = False
print "Unbanning user failed"
else:
receiver.sendMessage(contactName + " has not been banned")
unbanning = False
if muteSender == sid:
muteSender = ""
if contactId in mutedList:
receiver.sendMessage("This user has already been muted")
elif contactId in bots or contactId in owners or contactId in admins:
receiver.sendMessage("Friendly bots, owners or admins cannot be muted")
else:
mutedList.append(contactId)
mutedNames.append(contactName)
receiver.sendMessage(contactName + " has been silenced")
try:
file = open("txt files/muted.txt","w")
file.write("\n".join(mutedList))
file.close()
file = open("txt files/mutedNames.txt","w")
file.write("\n".join(mutedNames))
file.close()
except:
print "writing muted list failed"
if unmuteSender == sid:
unmuteSender = ""
if contactId in mutedList:
index = mutedList.index(contactId)
mutedList.pop(index)
mutedNames.pop(index)
receiver.sendMessage(contactName + " has been unsilenced")
try:
file = open("txt files/muted.txt","w")
file.write("\n".join(mutedList))
file.close()
file = open("txt files/mutedNames.txt","w")
file.write("\n".join(mutedNames))
file.close()
except:
print "writing muted list failed"
else:
receiver.sendMessage(contactName + " is not muted")
if message.text == None:
check = False
else:
msg = message.text.lower()
msg = " ".join(msg.split())
if check:
if receiver.id in client5._getGroupIdsJoined():
#user commands
if sid in admins or sid in owners:
#admin commands
if msg == botName + "adminlist":
staffText = "UW Bots\n"
adminText = "\n**Admins**\n\n"
getal1 = 0
for admin in admins:
adminObj = client5._findAndAddContactsByMid(admin)
adminName = (adminObj[admin].displayName)
adminText += str(getal1) + " - " + adminName
if getal1 + 1 < len(owners) + len(admins):
adminText += "\n"
getal1 += 1
staffText += adminText
receiver.sendMessage(staffText)
if msg == botName + "banlist":
nameText = ""
for name in bannedNames:
nameText += "- " +name +"\n"
bannedText = "UW Bots\n\nBanned users:\n\n" + nameText
receiver.sendMessage(bannedText)
if msg == botName + "admin commands":
commands = []
adminCommands = ["lurk on","lurk off","cancelall","@bye","welcomemsg","groupcast","adminlist","banlist"]
ownerCommands = []
commandCount = 1
commandMsg = "UW Bots\n\n"
for command in commands:
commandMsg += str(commandCount) + ". " +botName +command + "\n"
commandCount += 1
adminCommandMsg = "\nAdmin commands:\n\n"
adminCommandCount = 1
for command in adminCommands:
adminCommandMsg += str(adminCommandCount) + ". " +botName +command + "\n"
adminCommandCount += 1
ownerCommandMsg = "\nOwner commands:\n\n"
ownerCommandCount = 1
for command in ownerCommands:
ownerCommandMsg += str(ownerCommandCount) + ". " +botName +command + "\n"
ownerCommandCount += 1
receiver.sendMessage(commandMsg + adminCommandMsg +str(adminCommandCount) +". botname\n" +str(adminCommandCount + 1)+". ban\n" +str(adminCommandCount + 3) +". unban\n")
if message.text.lower().startswith("kick "):
if 'MENTION' in message.contentMetadata.keys() != None:
names = re.findall(r'@(\w+)', message.text)
mention = ast.literal_eval(message.contentMetadata['MENTION'])
mentionees = mention['MENTIONEES']
for mention in mentionees:
client5._kickoutFromGroup(receiver.id, [mention['M']])
if sid == groupcastSender:
groupcastSender = ""
client5.refreshGroups()
groups = client5.groups
for group in groups:
try:
group.sendMessage("Groupcast from "+sender.name+": "+message.text)
except:
print "Sending groupcast failed"
if msg == botName + "lurk on":
if lurking:
receiver.sendMessage("Already lurking..")
else:
lurking = True
lurkGroup = receiver
receiver.sendMessage("Lurking...")
if msg == botName + "lurk off":
if lurking:
lurking = False
lurkGroup = ""
getal2 = 0
lurkPreMessage = ""
for user in usersThatRead:
lurkPreMessage += str(getal2) + " - " + user
if getal2 + 1 < len(usersThatRead):
lurkPreMessage += "\n"
getal2 += 1
lurkMessage = "UW Bots\n\nLurk result:\n\n" + lurkPreMessage
receiver.sendMessage(lurkMessage)
else:
receiver.sendMessage("Lurking is not enabled")
if msg == botName + "@bye" or msg == botName + "bok op":
receiver.sendMessage("Bye! "+receiver.name)
client5._leaveGroup(receiver.id)
if msg == "cancel":
banning = False
unbanning = False
addOwner = False
addAdmin = False
delAdmin = False
delOwner = False
muteSender = False
unmuteSender = False
addbotSender = False
delBot = False
changestatusmessageSender = False
receiver.sendMessage("Send a contact cancelled")
if msg == "ban":
banning = True
unbanning = False
addOwner = False
addAdmin = False
delAdmin = False
delOwner = False
delBot = False
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
banSender = sid
receiver.sendMessage("Send a contact to ban")
if msg == "unban":
banning = False
unbanning = True
addOwner = False
addAdmin = False
delAdmin = False
delOwner = False
delBot = False
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
unbanSender = sid
receiver.sendMessage("Send a contact to unban")
if msg == botName + "cancelall":
if cancelall:
cancelall = False
receiver.sendMessage("Invites are now enabled")
else:
cancelall = True
receiver.sendMessage("Cancelling all invites..")
try:
group = client5.getGroupById(receiver.id)
pendingInvitations = group.invitee
pendingInvitations = [o.mid for o in pendingInvitations]
client5._cancelGroupInvitation(receiver.id,pendingInvitations)
except:
print "Could not cancel invitation(s)"
if welcomeSender == sid:
welcomeSender = ""
welcomeMsg = "%s%s" % (message.text[0].upper(), message.text[1:])
try:
file = open("txt files/welcome.txt","w")
file.write(welcomeMsg)
file.close()
receiver.sendMessage("New welcome message: "+welcomeMsg)
except:
receiver.sendMessage("Could not set welcome message, please try again.")
if changebotnameSender == sid:
changebotnameSender = ""
botName = msg + " "
client5._client_out.updateProfileAttribute(0,2,message.text)
if changestatusmessageSender == sid:
changestatusmessageSender = ""
client5._client_out.updateProfileAttribute(0,16,message.text)
if msg == botName + "welcomemsg":
welcomeSender = sid
receiver.sendMessage("Send your desired welcome message.")
if msg == "botname":
receiver.sendMessage("Current bot name: "+botName)
if msg == "test pic":
receiver.sendImage("img/tenor.gif")
if msg == botName + "groupcast":
groupcastSender = sid
receiver.sendMessage("Send a message to be groupcasted")
if sid in owners:
#owner commands
if msg == botName + "statusmessage":
changestatusmessageSender = sid
receiver.sendMessage("What should be my statusmessage?")
if msg == botName + "staff":
staffText = "UW Bots\n\n***Owners***\n\n"
adminText = "\n**Admins**\n\n"
getal1 = 0
for owner in owners:
ownerObj = client5._findAndAddContactsByMid(owner)
ownerName = (ownerObj[owner].displayName)
staffText += str(getal1) + " - " + ownerName + "\n"
getal1 += 1
for admin in admins:
adminObj = client5._findAndAddContactsByMid(admin)
adminName = (adminObj[admin].displayName)
adminText += str(getal1) + " - " + adminName
if getal1 + 1 < len(owners) + len(admins):
adminText += "\n"
getal1 += 1
staffText += adminText
receiver.sendMessage(staffText)
if msg.startswith(botName + "staff "):
msg = msg.split()[2]
if msg.isdigit():
if int(msg) < len(staff):
receiver.sendContact(staff[int(msg)])
if msg == botName + "owner commands":
commands = []
adminCommands = []
ownerCommands = ["change botname","copy","staff","staff [x]","statusmessage","mute","unmute","mutelist"]
commandCount = 1
commandMsg = "UW Bots\n\n"
for command in commands:
commandMsg += str(commandCount) + ". " +botName +command + "\n"
commandCount += 1
adminCommandMsg = "\nAdmin commands:\n\n"
adminCommandCount = 1
for command in adminCommands:
adminCommandMsg += str(adminCommandCount) + ". " +botName +command + "\n"
adminCommandCount += 1
ownerCommandMsg = "\nOwner commands:\n\n"
ownerCommandCount = 1
for command in ownerCommands:
ownerCommandMsg += str(ownerCommandCount) + ". " +botName +command + "\n"
ownerCommandCount += 1
receiver.sendMessage(commandMsg + ownerCommandMsg +str(ownerCommandCount + 1) +". deladmin\n" +str(ownerCommandCount + 2) +". addowner\n" +str(ownerCommandCount + 3) +". addadmin\n" +str(ownerCommandCount + 4) +". delowner\n" +str(ownerCommandCount + 5) +". addbot\n" +str(ownerCommandCount + 6) +". delbot")
if msg == botName + "change botname":
changebotnameSender = sid
receiver.sendMessage("How should I be called?")
if msg == botName + "copy":
copySender = sid
receiver.sendMessage("Send a contact to be copied")
if msg == "addbot":
banning = False
unbanning = False
addOwner = False
addAdmin = False
delAdmin = False
delOwner = False
muteSender = False
unmuteSender = False
delBot = False
changestatusmessageSender = False
addbotSender = sid
receiver.sendMessage("Send contact of bot")
if msg == "addowner":
addAdmin = False
addOwner = True
delAdmin = False
banning = False
unbanning = False
delOwner = False
delBot = False
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
ownerSender = sid
receiver.sendMessage("Send a contact to make owner")
if msg == "addadmin":
addOwner = False
addAdmin = True
delAdmin = False
banning = False
unbanning = False
delOwner = False
delBot = False
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
staffSender = sid
receiver.sendMessage("Send a contact to make admin")
if msg == "deladmin":
addAdmin = False
addOwner = False
banning = False
unbanning = False
delAdmin = True
delOwner = False
delBot = False
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
delstaffSender = sid
receiver.sendMessage("Send a contact to remove as admin")
if msg == "delowner":
addAdmin = False
addOwner = False
banning = False
unbanning = False
delAdmin = False
delBot = False
delOwner = True
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
delstaffSender = sid
receiver.sendMessage("Send a contact to remove as owner")
if msg == "delbot":
addAdmin = False
addOwner = False
banning = False
unbanning = False
delAdmin = False
delOwner = False
delBot = True
unmuteSender = False
addbotSender = False
changestatusmessageSender = False
delbotSender = sid
receiver.sendMessage("Send a contact to remove as a bot")
if msg == botName + "mute":
banning = False
unbanning = False
addOwner = False
addAdmin = False
delAdmin = False
delOwner = False
addbotSender = False
delBot = False
changestatusmessageSender = False
muteSender = sid
unmuteSender = ""
receiver.sendMessage("Send a contact to mute")
if msg == botName + "unmute":
banning = False
unbanning = False
addOwner = False
addAdmin = False
delAdmin = False
delOwner = False
addbotSender = False
delBot = False
changestatusmessageSender = False
unmuteSender = sid
muteSender = ""
receiver.sendMessage("Send a contact to unmute")
if msg == botName + "mutelist":
muteMsg = "UW's Bot\n\nList of muted users:\n\n"
for name in mutedNames:
muteMsg += "- " + name + "\n"
receiver.sendMessage(muteMsg)
if msg == botName + "nuke":
client5.refreshGroups()
try:
group = client5.getGroupById(receiver.id)
pendingInvitations = group.invitee
pendingInvitations = [o.mid for o in pendingInvitations]
client5._cancelGroupInvitation(receiver.id,pendingInvitations)
except:
print "Could not cancel invitation(s)"
try:
groep = client5.getGroupById(receiver.id)
members = groep.members
ids = [o.id for o in members]
ids = list(set(ids)-set(bots))
ids = list(set(ids)-set(staff))
client5._kickoutFromGroup(receiver.id,ids)
except:
print "Nuke failed"
elif operation.type == OT.NOTIFIED_INVITE_INTO_GROUP:
#only accept if inviter is bot or staff
if operation.param2 in bots or operation.param2 in owners or operation.param2 in admins:
client5._acceptGroupInvitation(operation.param1)
#if invited user is banned
invites = operation.param3.split("\x1e")
for invite in invites:
if invite in banned:
client5._cancelGroupInvitation(operation.param1,[invite])
#if cancelall is enabled
if cancelall:
for invite in invites:
if invite in bots:
invites.remove(invite)
try:
client5._cancelGroupInvitation(operation.param1,invites)
except:
print "Failed to cancel invite"
elif operation.type == OT.NOTIFIED_CANCEL_INVITATION_GROUP:
#check if invite to other bot gets canceled
invites = operation.param3.split("\x1e")
for invite in invites:
if invite in bots:
client5._inviteIntoGroup(operation.param1,[invite])
elif operation.type == OT.NOTIFIED_KICKOUT_FROM_GROUP:
#someone got kicked
if operation.param2 in admins or operation.param2 in bots or operation.param2 in owners:
#kicker is bot or staff so dont kick him
if operation.param3 in admins or operation.param3 in bots or operation.param3 in owners:
#inviting bot or staff back
client5._inviteIntoGroup(operation.param1,[operation.param3])
else:
print "Admin kicked user so don't invite back"
else:
client5._kickoutFromGroup(operation.param1,[operation.param2])
try:
banned.append(operation.param2)
bannedfunc()
bannedUser = client5._findAndAddContactsByMid(operation.param2)
bannedUserName = (bannedUser[operation.param2].displayName)
bannedNames.append(bannedUserName)
file = open("txt files/banned.txt","w")
file.write("\n".join(banned))
file.close()
file = open("txt files/bannedNames.txt","w")
file.write("\n".join(bannedNames))
file.close()
except:
print "Banning user failed"
client5._inviteIntoGroup(operation.param1,[operation.param3])
elif operation.type == OT.NOTIFIED_READ_MESSAGE:
if lurking:
groupMembers = lurkGroup.members
memberNames = [o.name for o in groupMembers]
memberIds = [o.id for o in groupMembers]
for x in range(0, len(memberIds)):
if memberIds[x] == operation.param2:
usersThatRead.append(memberNames[x])
elif operation.type == OT.NOTIFIED_ACCEPT_GROUP_INVITATION:
#someone joined the group
if operation.param2 in banned:
client5._kickoutFromGroup(operation.param1,[operation.param2])
elif operation.param2 not in bots:
receiver = client5.getContactOrRoomOrGroupById(operation.param1)
try:
file = open("txt files/welcome.txt","r")
content = file.read()
file.close()
receiver.sendMessage(content)
except:
print "failed to send welcome msg"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment