chevron_left chevron_right
Login Register invert_colors photo_library


Stay updated and chat with others! - Join the Discord!
Thread Rating:
  • 0 Vote(s) - 0 Average
Thread Closed 


Tutorial Chatango BOT commands filter_list
Author
Message
Chatango BOT commands #1
This tutorial is a follow-up of Zeb's original [TUTORIAL] CHATANGO BOT TUTORIAL. This is also not endorsed by Zeb himself.

Let's begin before I grow wrinckles.

We need a prefix for commands. Without this we won't have any working commands aside from the non-prefixed ones.

For all commands in this tutorial to work import a bit more than just ch.py. Just copy and paste the following into the imports section of your BOT.

Code:
import sys
import os
import cgi
import traceback
import time
import urllib
import datetime
import binascii
import json
import threading
import random
from xml.etree import cElementTree as ET

if sys.version_info[0] > 2:
    import urllib.request as urlreq
else:
    import urllib2 as urlreq

onConnect(self, room):
room.message("Connected.")
Print("Connected")

onReronnect(self, room):
print("Reconnected")

onDisconnect(self, room):
Print("Disconnected")

onMessage(self, room, user, message):

prefix = "/"

My bot prefix is a backslash for easy use. That's just me.

We will also need a way to split commands, and arguments. So let's add those materials.

Code:
onMessage(self, room, user, message):

prefix = "/"

msgdata = message.body.split(" ",1)
        if len(msgdata) > 1:
            cmd, args = msgdata[0], msgdata[1]
        else:
            cmd, args = msgdata[0],""
        cmd=cmd.lower()

        if len(cmd) >0:
            if cmd[0]==prefix:
                used_prefix = True
                cmd = cmd[1:]
            else:
                used_prefix= False
        else:
            return

We also should add a way to determine when to ignore commands. Say if you do /say /say, the bot will do /say twice until it can't say anything else. This being said we can't have that. Infinite loops are bad unless useful. You're going to be adding all of this under your onMessage, unless another specified location is given.

You're going to have to add if self.user == user: return.

Code:
onMessage(self, room, user, message):

prefix = "/"

if self.user == user: return

msgdata = message.body.split(" ",1)
        if len(msgdata) > 1:
            cmd, args = msgdata[0], msgdata[1]
        else:
            cmd, args = msgdata[0],""
        cmd=cmd.lower()

        if len(cmd) >0:
            if cmd[0]==prefix:
                used_prefix = True
                cmd = cmd[1:]
            else:
                used_prefix= False
        else:
            return

And print if a user says something.

Code:
onMessage(self, room, user, message):

print(user.name+": "+message.body)

prefix = "/"

if self.user == user: return

msgdata = message.body.split(" ",1)
        if len(msgdata) > 1:
            cmd, args = msgdata[0], msgdata[1]
        else:
            cmd, args = msgdata[0],""
        cmd=cmd.lower()

        if len(cmd) >0:
            if cmd[0]==prefix:
                used_prefix = True
                cmd = cmd[1:]
            else:
                used_prefix= False
        else:
            return

Let's move on to a youtube command. Which was mention in Zeb's tutorial as a reply. However, I am doing this to help clear up any misconception.

Code:
elif used_prefix and cmd=="youtube" and len(args) > 0:
            try:
                yword=args.replace(" ","_")
                ydata= urlreq.urlopen("http://gdata.youtube.com/feeds/api/videos?vq="+yword+"&racy=include&orderby=relevance&max-results=1")
                yread= str(ydata.read())
                if "<openSearch:totalResults>0</openSearch:totalResults>" in yread:
                    room.message("No results found for "+args)
                else:
                    trash , yclean=yread.split("<media:player url='http://www.youtube.com/watch?v=",1)
                    yclean , trash=yclean.split("&amp;",1)
                    room.message("http://http://www.youtube.com/watch?v="+yclean,True)
            except:
                room.message("Error.")

What this is telling the bot to do is go to a url, open it up, read it's code, and report back in a chat message if the video does not exist, show the video itself, or show an error.

Next is the profile command.

Code:
elif used_prefix and cmd=="profile" and len(args) > 0:
            try:
                name=args
                
                pdata= urlreq.urlopen("http://st.chatango.com/profileimg/"+args[:1]+"/"+args[1:2]+"/"+args+"/mod1.xml")
                pread= str(pdata.read())
                if "<img style" in pread:
                    room.message(args+" is not (yet) a chatango username.")
                else:
                    trash , pclean=pread.split("<body>",1)
                    pclean , trash=pclean.split("</body>",1)
                    room.message(urllib.parse.unquote(''+pclean+''"<br>"), True)
            except:
                room.message(args+" is not (yet) a chatango username.")

This does the same as the youtube command, but instead it searches profiles. Same concept though, so you should be able to grasp it easily.

We're going to do a die command so that you can easily stop the bot.

Code:
elif used_prefix and cmd=="die":
            if user.name.lower() == "yourusernamehere":
                room.message("Saved data.")
                print("[INFO][DATA][CMD]Saved data.")
                f.close
                room.message("[INFO][CMD]KILL COMMAND IN PROGRESS.")
                time.sleep(1)              
                self.stop()
            else:
                room.message("[INFO][CMD]KILL COMMAND FAILED.")

The command basically tells the bot to stop ONLY on the command of the specified user. If a user that is not specified tries the command it will say "[INFO][CMD]KILL COMMAND FAILED." and return to it's normal state.

Announce commands are VERY useful. They are used to send a message to all chatrooms the bot is in. Useful for bots such as botteh.

Code:
elif used_prefix and cmd == "anc" and len(args) > 0:
            if user.name.lower() == "yourusernamehere":
                for _room in self.rooms:
                    _room.message("Announcement from "+user.name.title()+": "+args)
            else:
                room.message("Owners only, BUB")

And we can't forget the all time famous say command.

Code:
elif used_prefix and cmd == "say":
            if args:
                room.message(args)
            else:
                room.message("Nothing to say.")

Once more this tutorial is a follow-up of Zeb's [TUTORIAL] CHATANGO BOT TUTORIAL. And again this is also not endorsed by Zeb himself. If you have any questions for a command, or comments, peanuts, popcorn, anything slap it down below. I might be able to help you.

If you want to see my bot in action go to http://intellectchat.chatango.com/


RE: Chatango BOT commands #2
Also

Kill commands help.

elif used_prefix and cmd=="kill":
time.sleep(1)
self.stop()


RE: Chatango BOT commands #3
Is it possible to adapt something like this, built with py, for use with multiple people, such as users with different levels of permissions on what they can use? And how would one set that up?
free @pvnk


RE: Chatango BOT commands #4
(12-12-2013, 07:15 AM)Satan Wrote: Is it possible to adapt something like this, built with py, for use with multiple people, such as users with different levels of permissions on what they can use? And how would one set that up?

Above the onMessage you would put

Code:
def getAccess(self, user):
        if user.name.lower() == "username here": return 1
        if user.name.lower() == "username here": return 1
        else: return 0

And if you want to make a command permission specific you would put

Code:
elif used_prefix and cmd=="cmdhere":
    if self.getAccess(user) == 1:
        ~stuffs here~
    else:
        room.message("No permission.")

Here's a few examples from my bot:

Code:
def getAccess(self, user):
        if user.name in blacklist: return 3
        if user.name.lower() == "duubz": return 2
        if user.name.lower() == "fecks": return 2
        if user.name in whitelist: return 1
        else: return 0
Code:
elif used_prefix and cmd=="kill":
            if self.getAccess(user) == 2:
                print("[INFO][DATA][CMD]Saved data: Nicknames")
                f= open("nicks.txt","w")
                for user in nicks:
                    nick = json.loads(nicks[user])
                    f.write(json.dumps([user,nick])+"\n")
                f.close
                f = open("whitelist.txt", "w")
                f.write("\n".join(whitelist))
                f.close()
                f = open("blacklist.txt","w")
                f.write("\n".join(blacklist))
                f.close()
                time.sleep(1)
                self.stop()
                f = open("rooms.txt","w")
                f.write("\n".join(rooms))
                f.close()
            else:
                room.message("Kill command failed. Insufficient permissions.")


RE: Chatango BOT commands #5
Ahh cool cool, thanks. This could be adapted for a rank type system, yeah? instead of declaring a username, declare it for use with a usergroup, define the usergroup, and have it pull whos in the usergroup from a txt file. Something like that?
free @pvnk


RE: Chatango BOT commands #6
(12-12-2013, 06:44 PM)Satan Wrote: Ahh cool cool, thanks. This could be adapted for a rank type system, yeah? instead of declaring a username, declare it for use with a usergroup, define the usergroup, and have it pull whos in the usergroup from a txt file. Something like that?

Like a whitelist?

Above the bot class put
Code:
whitelist = []
f = open("whitelist.txt", "r")
print("[INFO][DATA]Loading whitelist.")
time.sleep(1)
for name in f.readlines():
    if len(name.strip())>0: whitelist.append(name.strip())
f.close()
This is editable to your needs.

You're looking for this:
Code:
adminlist = []
f = open("adminlist.txt", "r")
print("[INFO][DATA]Loading adminlist.")
time.sleep(1)
for name in f.readlines():
    if len(name.strip())>0: adminlist.append(name.strip())
f.close()

The permissions would ve about the same, but instead:
Code:
def getAccess(self, user):
        if user.name in adminlist: return 1
        else: return 0

I recommend you have a global permission set so that you can always have a "back end" if you will incase the administrator list is somehow wiped.

Code:
def getAccess(self, user):
        if user.name in adminlist: return 1
        if user.name.lower() == "username here": return 1
        else: return 0

And you can put any number you want to be the level. I am using 1 as an example.

To add the admins you'd do this:

Code:
elif used_prefix and cmd == "admin":
            if len(args) >= 3:
                do, name = args.lower().split(" ", 1)
                if self.getAccess(ch.User(name)) > 2:
                    room.message("No.")
                    return
                if do == "add":
                    if self.getAccess(user) == 1:
                        if name in adminlist:
                            room.message("%s is already registered in my database." % name, True)
                        else:
                            adminlist.append(name)
                            room.message("Successfully added to adminlist.")
                    else:
                        room.message("%s it has not been possible to connect your call please hang up and try again" % user.name)
                elif do == "remove":
                    if self.getAccess(user) <= 1:
                        room.message("Invalid permission node.")
                        return
                    if name not in adminlist: room.message("%s isn't registered in my database." % name, True)
                    else:
                        adminlist.remove(name)
                        room.message("%s has been removed" % name, True)
                else:
                    room.message(">_>", True)
            else:
                if len(adminlist) == 0: room.message("I have no administrators.", True)
                elif len(adminlist) == 1: room.message("I have 1 administrator.", True)
                else: room.message("I have %s administrators." % len(adminlist), True)

I recon that you change your level to be higher than an admins, like 2 so that other admins can't make there friends admins without your permission. You'd have to change the file to return your username as a 2 and edit the line in the command where it says
" if do == "add":
if self.getAccess(user) == 1:"
and make it a 2 instead. Same with this line here;

"elif do == "remove":
if self.getAccess(user) <= 1:"

Make the "<= 1", "<= 2". That basically says nobody under level 2 can use the command to remove an admin.

The command is used like this:
/admin add username-here
/admin remove username-here

And to check how many administrators you have;
/admin

Once you got all of this make sure that adminlist.txt is located in your folder that contains the bot.


RE: Chatango BOT commands #7
Code:
elif used_prefix and cmd=="pm" and len(args) > 0:
            try:
                name = args.split()[0].lower()
                personalm = " ".join(args.split()[1:])
                self.pm.message(ch.User(name), "Message from "+user.name.capitalize()+": \""+personalm.capitalize()+"\"")
                room.message("Message sent to "+name.capitalize()+"!")
            except:
                room.message("Error sending message.")

Just remember that if you're PM restricted like me ( You can't message anyone who doesn't message you first, or if you're not in the other user's friendlist ) then your bot will have the same effect because of ip tracing.







Users browsing this thread: 1 Guest(s)