예제 #1
0
def main():
    input_token = input("token: ")
    client = Client.from_token(input_token)

    x = []
    i = 1
    print("Targets")
    print("0 - Quit")
    for chat in client.chats.list():
        print(str(i) + ' - ', end="")
        print(chat.other_user['name'])
        x.append(chat)
        i += 1

    message = "fck"
    i = 1
    while (True):
        '''
        input_target = input("target: ")

        if input_target == '0':
            break
        
        input_message = input("message: ")
        '''
        #x[int(input_target)-1].post(text = input_message)
        x[int(2) - 1].post(text="Yo where you at?")
        print("message sent to: ", end="")
        print(x[1])
        print("#: ")
        print(i)
        i += 1
        '''
예제 #2
0
def init():
    global token, client, session, bots, headers, botID, botIDs, groupIDs, messageManager, index, indexDict, members, memList
    token = "*"

    client = Client.from_token(token)
    session = client.session
    bots = Bots(session)
    headers = {
        'x-rapidapi-host': "apidojo-yahoo-finance-v1.p.rapidapi.com",
        'x-rapidapi-key': "*"
    }

    # bot 0 = test
    # bot 1 = real
    bot = 0
    run = True
    botIDs = ['*', '*']
    groupIDs = ['*', '*']
    index = 0
    indexDict = {}
    botID = botIDs[bot]

    messageManager = Messages(session, groupIDs[bot])

    members = client.groups.get(groupIDs[bot]).members

    memList = list()
    for member in members:
        memList.append(Portfolio(member.id))
        memList[index].name = member.nickname
        indexDict[member.nickname] = index
        index = index + 1
예제 #3
0
def lambda_handler(event,context):
  # test=1
  if test == 1:
    access_token=access_token_gordon
    group_name='PJW Calling Email Method'
  else:
    group_name='2017-2018 UT Captains'
    access_token=access_token_rishabh
  curr_date=datetime.datetime.now()
  weekday=curr_date.weekday()
  next_week=curr_date+datetime.timedelta(days=7)
  dt_str=str(next_week.month)+'/'+str(next_week.day)

# Hardcoded inputs, these need to be changed to suit your needs
  if weekday==7 or weekday == 2 or weekday == 3:
    if weekday==7:
      msg="PJW Calling for next Sunday 8-10pm "+dt_str+"\n1. Greg South\n2. Greg North\n3. Trophy Room"
    elif weekday==2:
      msg="PJW Calling for next Tuesday 10-12pm "+dt_str+"\n1. Greg South\n2. Greg North\n3. Trophy Room"
    elif weekday==3:
      msg="PJW Calling for next Wednesday 10-12pm "+dt_str+"\n1. Greg South\n2. Greg North\n3. Trophy Room"

    client=Client.from_token(access_token)

    for group in client.groups.list_all():
      if group.name==group_name:
        group.post(text=msg)
예제 #4
0
    def __init__(self, config):
        self._client = Client.from_token(config.get('token'))
        self._groups = []

        for group in client.groups.list(omit="memberships")
          if group.id == '49117054'
            self._groups.append( group )
예제 #5
0
def makeGroup(n, usrList):
    client = Client.from_token('jI9arGAkDrtNWAhKdKLnjaj182R2L7RLV7q9odFj')
    now = datetime.datetime.now()
    nDate = n + now.strftime()
    new_group = client.groups.create(name=nDate)
    for i in usrList:
        new_group.memberships.add(i[0], None, i[1], None)
예제 #6
0
def fetch_data():
    if 'client_key' not in session:
        #do some sort of error
        pass
    else:
        client = Client.from_token(session['client_key'])
    return client
예제 #7
0
def groupMeGenerateGroup(studyGroup):
    # Generate client that does the work
    client = Client.from_token(GROUPME_TOKEN)
    # Create the group itself
    new_group = client.groups.create(name=studyGroup.name)

    studyGroup.group_id = new_group.group_id
    studyGroup.save()
def grab_song_links(GroupMe_Token, GroupMe_Group_Name):

    # Authorization Step, Returns Client
    client = Client.from_token(GroupMe_Token)

    # Grabs Group Chat
    group_chat = get_group_chat(client, GroupMe_Group_Name)

    # Grabs last message ID from previous runs
    last_message = get_last_id()

    # Grabs list of messages after last message
    try:
        list_of_messages = list(group_chat.messages.list_after(last_message))

    #if there is no ID/not recognized, grabs every single message in the list
    except:
        list_of_messages = list(group_chat.messages.list().autopage())

    # Note: Groupy list() function always returns a page of messages even if you
    # include a since_id so spotify song adder will always have to check if the song
    # isn't added already. Spotify song adder will need that function anyways to
    # make sure that the song hasn't been added by someone before.

    # Initializes list of songs to add to spotify

    list_of_songs = []

    for message in list_of_messages:

        if message.text != None:

            x = message.text[message.text.find("https://open.spotify.com/track"
                                               ):message.text.find(" ")]
            if x:
                list_of_songs.append(x)

    # Creates new log ID
    last_message = list_of_messages[0].id

    filename = "log.txt"
    # opening the file with w+ mode truncates the file
    f = open(filename, "w+")
    f.close()

    logging.basicConfig(filename=("log.txt"),
                        level=logging.DEBUG,
                        format='%(message)s')
    logging.info(last_message)

    # Returns a reversed list as the list of messages is returned in reversed order.
    # Reversing the final list ensures that the songs are added in the same order they were sent.

    list_of_songs.reverse()

    return list_of_songs
예제 #9
0
def create_groupme_api():
    keys = readKeys()
    groupme_key = keys['groupme']['access_token']
    client = Client.from_token(groupme_key)
    groups = list(client.groups.list_all())
    for group in groups:
        print(group.name)
        if group.name == 'Large Fry Larrys':
            lfl = group
    return lfl
예제 #10
0
def group_created(token):
    client = Client.from_token(token)
    groups = client.groups.list_all()

    group_created_times = {}
    for group in groups:
        group_created_times[group.name] = created_at(group)

    with open('Groups Created At.txt', 'w', encoding='utf8') as output:
        for name, timestamp in group_created_times.items():
            output.write(name + ': ' + timestamp + '\n')
예제 #11
0
def groupMeJoinGroup(studyGroup, student: Student):
    # Generate client that does the work
    client = Client.from_token(GROUPME_TOKEN)

    # Get group object
    try:
        group = client.groups.get(studyGroup.group_id)
    except:
        print("Failed to find group")
        return
    # group = None
    # for g in client.groups.list_all():
    #     if str(g.name) == studyGroup.name:
    #         group = g

    # Fancy out-of-library technique to do what I want - add via phone number
    mship = group.get_membership()
    memberships = Memberships(mship.manager.session, group_id=group.group_id)
    member = {
        'nickname': str(student.name),
        'phone_number': str(student.phone)
    }
    memberships.add_multiple(member)
    #result.poll(timeout=5, interval=0.1)
    time.sleep(1)
    try:
        group = client.groups.get(studyGroup.group_id)
    except:
        print("Failed to find group")
        return
    # Save their user id for later
    mem = None
    print(group.members)
    for m in group.members:
        print(str(m.nickname), str(student.name))
        if str(m.nickname) == str(student.name):
            mem = m
    studyGroup.save()
    try:
        print(type(mem))
        print(mem)
        print(mem.user_id)
        print(str(mem.user_id))
        if str(mem.user_id) != "None":
            print("Entered if statement")
            student.groupme_id = str(mem.user_id)
            student.save()
            print("Finished if statement")
        else:
            print("Skipped if statement")
    except:
        print("Failed to save")
        pass
예제 #12
0
def message_birdbrains(message, token_fn=TOKEN_FN):
    with open(token_fn, 'r') as token_file:
        token = token_file.read()
    token = token.replace("\n", "")
    client = Client.from_token(token)

    bird_brains = [
        group.name == 'Bird Brains' for group in client.groups.list()
    ]
    bird_brains = client.groups.list()[np.where(bird_brains)[0][0]]

    return bird_brains.post(text=message)
예제 #13
0
def load_logged_in_user():
    user_id = session.get('user_id')
    username = session.get('user_id')
    token = session.get('token')

    if user_id is None:
        g.user = None
    else:
        g.user = {
            "user_id": int(user_id),
            "username": username,
            "client": Client.from_token(token)
        }
예제 #14
0
    def __init__(self, cfg):
        self.token = cfg["ZeBanker"]["token"]
        self.groupme_group_id = cfg["ZeBanker"]["groupme_group_id"]
        self.donk_group_id = cfg["ZeBanker"]["donk_group_id"]
        self.output_dir = os.path.join(script_path, cfg["ZeBanker"]["output_dir_relative_to_script"])
        self.message = cfg["ZeBanker"]["message"] == "True"
        self.bot_id = cfg["ZeBanker"]["bot_id"]

        self.client = Client.from_token(self.token)
        self.groupme_group = self.get_group()
        self.banker = None
        self.new_messages = None
        self.command = ""
        self.commander = None
예제 #15
0
    def __init__(self):
        self.commands = {
            "!commands": self.list_commands,
        }

        self.commandDescriptions = {
            "!commands": "Lists all commands",
        }

        self.database = Database('GroupMe')

        self.Lastfm = LastfmCommands()
        self.commands.update(self.Lastfm.commands)
        self.commandDescriptions.update(self.Lastfm.commandDescriptions)
        self.client = Client.from_token(groupyToken)
        self.ran_tasks = False
예제 #16
0
def main(input_args):
    client = Client.from_token(input_args.token)
    if client is not None:
        stats_group = client.groups.get(input_args.groupid)
        print("Generating Stats for: " + stats_group.name)

        # Create a dict of members for name lookups
        print("Getting group members...")
        members = get_members(stats_group)
        print_members(members)

        # One last server update before grabbing everything
        print("Refreshing groups...")
        stats_group.refresh_from_server()
        #dump_chat_history_to_file(stats_group, "out.csv")
        dump_chat_history_to_file(stats_group, members)
예제 #17
0
def main():
    # Create groupy client from access token
    client = Client.from_token(Config.token)
    myGroup = findGroup(client, Config.groupName)
    # make sure group is newly refreshed
    myGroup.refresh_from_server()

    allMessages = list(myGroup.messages.list().autopage())

    memberList = []
    for member in myGroup.members:
        memberList.append((member.user_id, member.nickname))

    memberDict = memberDictBuilder(memberList, Config.keywords)

    countedMemberDict = getWordCounts(memberDict, allMessages, Config.keywords)

    displayData(countedMemberDict, memberList, Config.keywords)
예제 #18
0
    def __init__(self, input_dict):
        '''
        input dict  :   dictionary built with DataFromUser class with inputs
                        ['gm_token',
                        'group_name',
                        'log_file',
                        'sp_client_id',
                        'sp_client_secret',
                        'sp_redirect',
                        'sp_username',
                        'sp_user_id',
                        'sp_playlist_id',
                        'playlist_name']
                        to act as dictionary keys
        '''
        # Assign paramaters to class attributes
        self.__dict__.update(input_dict)
        self.sp_scope = "playlist-modify-public"

        # Groupme Client
        gp_client = Client.from_token(self.gm_token)

        # Groupme Groupchat
        groupchat = self.find_groupchat(gp_client)

        # Song URLs From Messages
        song_urls = self.get_tracks_from_groupchat(
            groupchat, self.find_last_checked_message(self.log_file))

        # If there are new songs in the groupchat:
        if song_urls:

            # Login to Spotify
            sp_cred = SpotifyOAuth(client_id=self.sp_client_id,
                                   client_secret=self.sp_client_secret,
                                   redirect_uri=self.sp_redirect,
                                   username=self.sp_username,
                                   scope=self.sp_scope)
            self.sp = spotipy.Spotify(client_credentials_manager=sp_cred)

            # Add songs to Spotify playlist
            self.add_songs_to_playlist(song_urls)
예제 #19
0
def groupMeLeaveGroup(studyGroup: StudyGroup, student: Student):
    # Generate client that does the work
    client = Client.from_token(GROUPME_TOKEN)

    # Get group object
    try:
        group = client.groups.get(studyGroup.group_id)
    except:
        print("Failed to find group")
        return

    # Assumes their user_id is known
    mem = None
    for m in group.members:
        if str(m.user_id) == str(student.groupme_id):
            mem = m
    try:
        mem.remove()
        mem.save()
    except:
        pass
예제 #20
0
def login():
    token = request.args.get('access_token')
    if not token is None:
        # Get client
        client = Client.from_token(token)
        error = None

        # Error check
        try:
            me = client.user.get_me()
        except:
            error = "Bad GroupMe login."

        if error is not None:
            flash(error)
        else:
            # Setup the session
            user_id = me["id"]
            username = me["name"]

            session.clear()
            session['user_id'] = user_id
            session['username'] = username
            session['token'] = token

            # Check for bot instances
            # Only useful in event of catastrophic DB failure
            bot_client = Bots(client.session)
            bots = bot_client.list()
            for bot in bots:
                if bot["name"] == config["name"]:
                    db = get_db()
                    if db.execute('SELECT * FROM bot WHERE group_id = ?',
                                  (bot["group_id"], )).fetchone() is None:
                        # This bot instance is unrecorded
                        bot_client.destroy(bot["bot_id"])

            return redirect(url_for('index'))

    return render_template('auth/login.html')
예제 #21
0
def post(groups=True, message='#mathMemeMonday', limit=10 ,targetFile='targets.txt',credFile='credientials.txt'):

    token=getStringFromFile('token',credFile)

    client = Client.from_token(token)
    targets=setTargetsFromFile(targetFile)
    postTo=[]
    i=0

    if(not groups):
        for chat in client.chats.list_all():
            if (chat.other_user['name'] in targets):
                print('Adding: '+chat.other_user['name']+' to reciving list')
                postTo.append(chat)
    else:
        for group in client.groups.list():
            if (group.id in targets):
                print('Adding: '+group.name+' to reciving list')
                postTo.append(group)

    for squad in postTo:
        while (i<limit):
            atts=[]
            if(not groups):
                print('Posting Meme '+str(i)+' to '+squad.other_user['name'])
            else:
                print('Posting Meme '+str(i)+' to '+squad.name)
            with open('meme'+str(i)+'.jpg','rb') as f:
                image=client.images.from_file(f)
            atts.append(image)
            mess=squad.post(text=message,attachments=atts)
            f.close()
            i+=1
        i=0

    while (i<10):
        os.remove('meme'+str(i)+'.jpg')
        i+=1

    print('All Memes Posted')
예제 #22
0
    def delete(self, *args, **kwargs):
        # Note this is a simple example. it only handles delete(),
        # and not replacing images in .save()
        print("deleting")
        group_id = None
        if (self.group_id != None):
            group_id = self.group_id

        super(StudyGroup, self).delete(*args, **kwargs)

        if (group_id != None):
            # Generate client that does the work
            client = Client.from_token(GROUPME_TOKEN)

            # Get group
            try:
                group = client.groups.get(group_id)
            except:
                print("Failed to find group")
                return
            print("destroying group")
            group.destroy()
예제 #23
0
from datetime import datetime
from Bot.LastfmCommands import LastfmCommands
from Database.Database import Database
from Token import bot_id, groupyToken, groupy_id
from groupy.client import Client
from groupy.api.attachments import Mentions, Image

client = Client.from_token(groupyToken)
group = client.groups.get(groupy_id)


class GroupmeCommandHandler:
    """The Groupme Command Handler Class.

    The command handler class is responsible for connecting the bot to API's and
    executing the commands. It contains the list of commands and their given
    descriptions; it also contains some default commands for controlling the bot.


    """
    def __init__(self):
        self.commands = {
            "!commands": self.list_commands,
        }

        self.commandDescriptions = {
            "!commands": "Lists all commands",
        }

        self.database = Database('GroupMe')
예제 #24
0
    "Sunday Brunch", "Sunday Dinner", "Monday Dinner", "Tuesday Dinner",
    "Wednesday Dinner", "Thursday Dinner"
]
DAY_OFFSETS = {
    "Sunday Brunch": 0,
    "Sunday Dinner": 0,
    "Monday Dinner": 1,
    "Tuesday Dinner": 2,
    "Wednesday Dinner": 3,
    "Thursday Dinner": 4
}
r = sr.Recognizer()

from groupy.client import Client
token = "d0d1772007dc0137492936e4528fcc3b"
client = Client.from_token(token)

#groups = client.groups.list(omit="memberships")
#To see what groupmes available
#for group in groups.autopage():
#    print(group.name)
group_chat_list = ["DH",
                   "2018"]  #list of stings that are in the groupchat name


def post_to_DH(message):
    groups = client.groups.list(omit="memberships")
    for group in groups.autopage():
        if all([a in group.name for a in group_chat_list]):
            message = group.post(text=message)
# import json file if present
try:
    with open('secret.json', 'r') as f:
        DATA = json.load(f)
        if not DATA:
            DATA = {}
except (NameError, FileNotFoundError):
    print(
        'WARNING: no secret.json file present in project root, ignoring update'
    )

# config vars
# os.environ == (heroku) environment global vars
# replace with local values if desired
# ex for each above definition
try:
    # 1234567890abcdef1234567890abcdef
    GROUPME_TOKEN = os.getenv('GROUPME_TOKEN') or DATA['GROUPME_TOKEN']
    CLIENT = Client.from_token(GROUPME_TOKEN)
except NameError:
    raise Exception('***all necessary global config not defined***')


def getIDs():
    for group in CLIENT.groups.list(omit="memberships").autopage():
        print(group.name + ' (' + group.id + ')')


if __name__ == '__getIDs__':
    getIDs()
예제 #26
0
from groupy.client import Client
from time import sleep
from dotenv import load_dotenv
from os import getenv

load_dotenv()
shakes = open('corpora/shakespeare.txt', 'r')
groupme = Client.from_token(getenv('GROUPME_TOKEN'))
dingus_parade = [
    group for group in groupme.groups.list() if group.id == '19442193'
][0]

for line in shakes:
    if line != "\n":
        dingus_parade.post(line)
        sleep(3)
예제 #27
0
def main():
    """
    :return: sets up the groups the bot will listen and then initialize the threads
    """
    args = parser.parse_args()
    config_parser = configparser.ConfigParser()
    config_path = os.path.abspath(args.config)
    config_parser.read(config_path)
    try:
        chat_key = config_parser['keys']['groupme']
    except KeyError:
        Utilities.log(f"Need groupme api key to continue")
        sys.exit(1)

    try:
        yt_key = config_parser['keys']['youtube']
    except KeyError:
        yt_key = None

    delim = config_parser['bot']['delim']
    refresh_group_interval = int(
        config_parser['bot']['refresh_group_interval'])
    consume_time = float(config_parser['bot']['consume_time'])

    client = Client.from_token(chat_key)
    groups = {}

    try:
        with open(os.path.abspath(args.groups), 'r') as all_groups:
            groups = json.load(all_groups)
    except FileNotFoundError:
        potential_groups = []
        group_file_path = os.path.abspath(args.groups)
        for group in client.groups.list():
            potential_groups.append((group.id, group.name))

        print("Which groups to use the bot for?")

        for index, pair in enumerate(potential_groups):
            print(f"{index + 1}: {pair[1]}")

        choices = input("Which ones (comma separated): ").split(",")
        chosen_groups = {}
        for choice in choices:
            try:
                chosen_groups[potential_groups[int(choice) - 1][1]] = {
                    "id": potential_groups[int(choice) - 1][0],
                    "enabled": True
                }
            except ValueError:
                pass
            except IndexError:
                pass

        with open(os.path.abspath(group_file_path), 'w') as finalized_groups:
            json.dump(chosen_groups,
                      finalized_groups,
                      sort_keys=True,
                      indent=2)
            print(f"created groups.json at {group_file_path}")
        groups = chosen_groups
    for group in groups:
        name = group
        group = groups[group]
        try:
            if group['enabled']:
                group = client.groups.get(group['id'])
                bot = Bot(group,
                          yt_key=yt_key,
                          delim=delim,
                          refresh_group_interval=refresh_group_interval)
                Utilities.log(f"creating thread for {group.name}")
                threading.Thread(target=consume,
                                 name=group.name,
                                 daemon=True,
                                 args=(bot, consume_time)).start()
        except (IndexError, groupy.exceptions.BadResponse,
                requests.exceptions.HTTPError):
            Utilities.log(f"'{name}' group doesn't exist")

    signal.signal(signal.SIGINT, shutdown_bot)

    Utilities.log(f"Bot started up successfully")
예제 #28
0
import os
from groupy.client import Client

GROUP_ID = 46649296
TOKEN = os.environ['GROUPME_ACCESS_TOKEN']
client = Client.from_token(TOKEN)

group = client.groups.get(id=GROUP_ID)

targets = [
    'Chike Iwuagwu', 'hiba hamid', 'AIDAN YOO(NOT SIMON)',
    'Walli Chen (penn daddy)', 'Simon', 'Nick Bausenwein (Penn)',
    'Eashan Sahai', 'AJ Manning', 'Margaret LaMarche', 'Rachel Wilson',
    'Nitin S', 'Mia McDonald', 'David Yang', 'David Lu', 'serin b',
    'Halsey Ziglar', 'Langston Luck', 'Sophie Hirt', 'Nick Bausenwein (Penn)',
    'Jacob K', 'Nicole Overton'
]

for member in group.members:
    if member.nickname in targets:
        print(member.remove())
예제 #29
0
import model, sample, encoder

from groupy.client import Client
import asyncio
import re
import time
import random

#Your GroupMe client token from the top right corner of https://dev.groupme.com/
CLI_TOKEN = "CLIENT TOKEN HERE"
GROUP_NAME = "GROUP NAME HERE"
BOT_NAME = "BOT NAME HERE"

#Init connection to groupMe client using your token
client = Client.from_token(CLI_TOKEN)

#Find the bot with name @BOT_NAME and store it as bot
for bot in client.bots.list():
    if bot.name == BOT_NAME:
        break

#Find the group with name @GROUP_NAME and store it as @group
for group in client.groups.list_all(omit="memberships"):
    if group.name == GROUP_NAME:
        break

memberList = group.members

#Precompile regular expressions for recognizing commands.
#Precompilation improves the speed of recognition
예제 #30
0
# RESOURCE: http://www.apnorton.com/blog/2017/02/28/How-I-wrote-a-Groupme-Chatbot-in-24-hours/

# IMPORTS
import os
import json
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from flask import Flask, request
from apscheduler.schedulers.blocking import BlockingScheduler
import groupy
from groupy.client import Client as groupmeClient
gmclient = groupmeClient.from_token('vW461v8rqQ8tya2YGf4J6cSWV5MUoVI2tuNHI60R')
for gmgroups in gmclient.groups.list():
    if gmgroups.name == 'AW log (updates only)':
        gmlog = gmgroups

#----------------from production log
from selenium import webdriver
#from selenium.webdriver.common.keys import Keys
import selenium.webdriver.chrome.options
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import time
from datetime import timedelta, datetime
from pytz import timezone
tztime = datetime.now(timezone('America/Los_Angeles'))
scope = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive'
]