<commit_before>"""
Module for collecting the utility functions dealing with mostly calendar
tasks, processing dates and creating time-based code.
"""

import datetime
import calendar as cdr

from django.core.handlers.wsgi import WSGIRequest
from django.http import Http404, HttpResponse
from django.db import IntegrityError

import simplejson

from timetracker.tracker.models import TrackingEntry, Tbluser
from timetracker.utils.database_errors import DUPLICATE_ENTRY

MONTH_MAP = {
    0: ('JAN', 'January'),
    1: ('FEB', 'February'),
    2: ('MAR', 'March'),
    3: ('APR', 'April'),
    4: ('MAY', 'May'),
    5: ('JUN', 'June'),
    6: ('JUL', 'July'),
    7: ('AUG', 'August'),
    8: ('SEP', 'September'),
    9: ('OCT', 'October'),
    10:('NOV', 'November'),
    11:('DEC', 'December')
}

def pad(string, padchr='0', amount=2):
    """
    Pads a string
    """
    string = str(string)

    if len(str(string)) < amount:
        pre = padchr * (amount - len(string))
        return pre+string

    return string

def get_request_data(form, request):

    """
    Given a form and a request object we pull out
    from the request what the form defines.

    i.e.

    form = {
        'data1': None
    }

    get_request_data(form, request) will then fill
    that data with what's in the request object.
    """

    data = dict()

    # get our form data
    for key in form:
        data[key] = request.POST.get(key, None)

    # get the user id from the session
    data['user_id'] = request.session['user_id']

    return data

def validate_time(start, end):

    """
    Validates the times given
    """

    shour, sminute = parse_time(start)
    ehour, eminute = parse_time(end)

    return (datetime.time(shour, sminute)
            < datetime.time(ehour, eminute))

def parse_time(timestring, type_of=int):

    """
    Given a time string will return a tuple of ints,
    i.e. "09:44" returns (9, 44) with the default args,
    you can pass any function to the type argument.
    """

    return map(type_of, timestring.split(":"))

def calendar_wrapper(function):
    """
    Decorator which checks if the calendar function was
    called as an ajax request or not, if so, then the
    the wrapper constructs the arguments for the call
    from the POST items
    """

    def inner(*args, **kwargs):
        """
        Checks argument length and constructs the call
        based on that.
        """

        if isinstance(args[0], WSGIRequest):
            request = args[0]
            try:
                eeid = request.POST.get('eeid', None)
                return HttpResponse(function(user=eeid))
            except Exception as e:
                return HttpResponse(str(e))

        else:
            return function(*args, **kwargs)

    return inner

@calendar_wrapper
def gen_calendar(year=datetime.datetime.today().year,
                 month=datetime.datetime.today().month,
                 day=datetime.datetime.today().day,
                 user=None):

    """
    Returns a HTML calendar, calling a database user to get their day-by-day
    entries and gives each day a special CSS class so that days can be styled
    individually.

    The generated HTML should be 'pretty printed' as well, so the output code
    should be pretty readable.
    """

    # django passes us Unicode strings
    year, month, day = int(year), int(month), int(day)

    if month-1 not in MONTH_MAP.keys():
        raise Http404

    # if we've generated December, link to the next year
    if month + 1 == 13:
        next_url = '"/calendar/%s/%s"' % (year + 1, 1)
    else:
        next_url = '"/calendar/%s/%s"' % (year, month + 1)

    # if we've generated January, link to the previous year
    if month - 1 == 0:
        previous_url = '"/calendar/%s/%s"' % (year - 1, 12)
    else:
        previous_url = '"/calendar/%s/%s"' % (year, month - 1)

    # need to use authorisation and sessions to get this
    # for testing we'll just grab the same db object
    database = Tbluser.objects.get(id__exact=user)

    # pull out the entries for the given month
    try:
        database = TrackingEntry.objects.filter(
            user=database.id,
            entry_date__year=year,
            entry_date__month=month
            )

    except TrackingEntry.DoesNotExist:
        # it seems Django still follows through with the assignment
        # when it raises an error, this is actually quite good because
        # we can treat the query set like normal
        pass

    # create a semi-sparsely populated n-dimensional
    # array with the month's days per week
    calendar_array = cdr.monthcalendar(
        int(year),
        int(month)
    )

    # creating a list holder for the strings
    # this is faster than concatenating the
    # strings as we go.
    cal_html = list()
    to_cal = cal_html.append

    # create the table header
    to_cal("""
\n\t\t\t""")

    to_cal("""

                  <

                {2}

                  >

\n""".format(previous_url,
                                next_url,
                                MONTH_MAP[int(month)-1][1]
                        )
           )

    # insert day names
    to_cal("""\n\t\t\t

                Mon
                Tue
                Wed
                Thu
                Fri
                Sat
                Sun

\n""")

    # each row in the calendar_array is a week
    # in the calendar, so create a new row
    for week_ in calendar_array:
        to_cal("""\n\t\t\t
\n""")

        for _day in week_:

            # the calendar_array fills extraneous days
            # with 0's, we can catch that and treat either
            # end of the calendar differently in the CSS
            if _day != 0:
                emptyclass = 'day-class empty-day'
            else:
                emptyclass = 'empty'

            # we've got the month in the query set,
            # so just query that set for individual days
            try:
                # get all the data from our in-memory query-set.
                data = database.get(entry_date__day=_day)

                # Pass these to the page so that the jQuery functions
                # get the function arguments to edit those elements
                vals = [
                    data.start_time.hour,
                    data.start_time.minute,
                    str(data.start_time)[0:5],
                    data.end_time.hour,
                    data.end_time.minute,
                    str(data.end_time)[0:5],
                    data.entry_date,
                    data.daytype,
                    _day,
                    data.id
                    ]

                to_cal("""\t\t\t\t
                       {8}	\n""".format(*vals)
                       )

            except TrackingEntry.DoesNotExist:

                # For clicking blank days to input the day quickly into the
                # box. An alternative to the datepicker
                if _day != 0:
                    entry_date_string = '-'.join(map(pad,
                                                     [year, month, _day]
                                                     )
                                                )
                else:
                    entry_date_string = ''

                # we don't want to write a 0 in the box
                _day = '&nbsp' if _day == 0 else _day

                # write in the box and give the empty boxes a way to clear
                # the form
                to_cal("""\t\t\t\t{2}	\n""".format(
                                                  entry_date_string,
                                                  emptyclass,
                                                  _day)
                                              )

        # close up that row
        to_cal("""\t\t\t
\n""")

    # close up the table
    to_cal("""\n
""")

    # join up the html and push it back
    return ''.join(cal_html)

def json_response(func):

    """
    Decorator function that when applied to a function which
    returns some json data will be turned into a HttpResponse

    This is useful because the call site can literally just
    call the function as it is without needed to make a http-
    response.
    """

    def inner(request):

        """
        Grabs the request object on the decorated and calls
        it
        """

        return HttpResponse(simplejson.dumps(func(request)),
                            mimetype="application/javscript")
    return inner

def request_check(func):

    """
    Decorator to check an incoming request against a few rules
    """

    def inner(request):

        """
        Pulls the request object off the decorated function
        """

        if not request.is_ajax():
            raise Http404

        if not request.session.get('user_id', None):
            # if there is no user id in the session
            # something weird is going on
            raise Http404

        return func(request)

    return inner

@request_check
@json_response
def ajax_add_entry(request):

    '''
    Adds a calendar entry asynchronously
    '''

    # object to dump form data into
    form = {
        'entry_date': None,
        'start_time': None,
        'end_time': None,
        'daytype': None,
        'breaks': None
    }

    # get the form data from the request object
    form.update(get_request_data(form, request))

    # create objects to put our data into
    json_data = dict()

    try:
        # server-side time validation
        if not validate_time(form['start_time'], form['end_time']):
            json_data['error'] = "Start time after end time"
            return json_data
    except ValueError:
        json_data['error'] = "Date Error"
        return json_data

    # need to add a breaks section to the form
    form['breaks'] = "00:15:00"

    try:
        entry = TrackingEntry(**form)
        entry.save()
    except IntegrityError as error:
        if error[0] == DUPLICATE_ENTRY:
            json_data['error'] = "There is a duplicate entry for this value"
        else:
            json_data['error'] = str(error)
        return json_data

    year, month, day = map(int,
                           form['entry_date'].split("-")
                           )

    calendar = gen_calendar(year, month, day,
                            form['user_id'])

    # if all went well
    json_data['success'] = True
    json_data['calendar'] = calendar
    return json_data

@request_check
@json_response
def ajax_delete_entry(request):
    """
    Asynchronously deletes an entry
    """

    form = {
        'hidden-id': None,
        'entry_date': None
    }

    # get the form data from the request object
    form.update(get_request_data(form, request))

    # create our json structure
    json_data = dict()

    if form['hidden-id']:
        try:
            # get the user and make sure that the user
            # assigned to the TrackingEntry is the same
            # as what's requesting the deletion
            user = Tbluser.objects.get(id__exact=form['user_id'])
            entry = TrackingEntry(id=form['hidden-id'],
                                  user=user)
            entry.delete()
        except Exception as error:
            json_data['error'] = str(error)
            return json_data

    year, month, day = map(int,
                           form['entry_date'].split("-")
                           )

    calendar = gen_calendar(year, month, day,
                            user=form['user_id'])

    # if all went well
    json_data['success'] = True
    json_data['calendar'] = calendar
    return json_data

@json_response
def ajax_error(error):

    """
    Returns a HttpResponse with JSON as a payload with the error
    code as the string that the function is called with
    """

    return {
        'success': False,
        'error': error
        }

@request_check
@json_response
def ajax_change_entry(request):

    '''
    Changes a calendar entry asynchronously
    '''

    # object to dump form data into
    form = {
        'entry_date': None,
        'start_time': None,
        'end_time': None,
        'daytype': None,
        'breaks': None,
        'hidden-id': None
    }

    # get the form data from the request object
    form.update(get_request_data(form, request))

    # create objects to put our data into
    json_data = dict()

    try:
        # server-side time validation
        if not validate_time(form['start_time'], form['end_time']):
            json_data['error'] = "Start time after end time"
            return json_data
    except ValueError:
        json_data['error'] = "Date Error"
        return json_data

    # need to add a breaks section to the form
    form['breaks'] = "00:15:00"

    if form['hidden-id']:
        try:
            # get the user and make sure that the user
            # assigned to the TrackingEntry is the same
            # as what's requesting the change
            user = Tbluser.objects.get(id__exact=form['user_id'])
            entry = TrackingEntry(id=form['hidden-id'],
                                  user=user)

            # change the fields on the retrieved entry
            entry.entry_date = form['entry_date']
            entry.start_time = form['start_time']
            entry.end_time = form['end_time']
            entry.daytype = form['daytype']
            entry.breaks = form['breaks']

            entry.save()

        except Exception as error:
            json_data['error'] = str(error)
            return json_data

    year, month, day = map(int,
                           form['entry_date'].split("-")
                           )

    calendar = gen_calendar(year, month, day,
                            form['user_id'])

    # if all went well
    json_data['success'] = True
    json_data['calendar'] = calendar
    return json_data
<commit_msg>Interception of the calendar calls is complete Each time the calendar is called, it is checked to see if it's an ajax request, if it is, then we construct the parameters from the POST dict<commit_after>"""
Module for collecting the utility functions dealing with mostly calendar
tasks, processing dates and creating time-based code.
"""

import datetime
import calendar as cdr

from django.core.handlers.wsgi import WSGIRequest
from django.http import Http404, HttpResponse
from django.db import IntegrityError

import simplejson

from timetracker.tracker.models import TrackingEntry, Tbluser
from timetracker.utils.database_errors import DUPLICATE_ENTRY

MONTH_MAP = {
    0: ('JAN', 'January'),
    1: ('FEB', 'February'),
    2: ('MAR', 'March'),
    3: ('APR', 'April'),
    4: ('MAY', 'May'),
    5: ('JUN', 'June'),
    6: ('JUL', 'July'),
    7: ('AUG', 'August'),
    8: ('SEP', 'September'),
    9: ('OCT', 'October'),
    10:('NOV', 'November'),
    11:('DEC', 'December')
}

def pad(string, padchr='0', amount=2):
    """
    Pads a string
    """
    string = str(string)

    if len(str(string)) < amount:
        pre = padchr * (amount - len(string))
        return pre+string

    return string

def get_request_data(form, request):

    """
    Given a form and a request object we pull out
    from the request what the form defines.

    i.e.

    form = {
        'data1': None
    }

    get_request_data(form, request) will then fill
    that data with what's in the request object.
    """

    data = dict()

    # get our form data
    for key in form:
        data[key] = request.POST.get(key, None)

    # get the user id from the session
    data['user_id'] = request.session['user_id']

    return data

def validate_time(start, end):

    """
    Validates the times given
    """

    shour, sminute = parse_time(start)
    ehour, eminute = parse_time(end)

    return (datetime.time(shour, sminute)
            < datetime.time(ehour, eminute))

def parse_time(timestring, type_of=int):

    """
    Given a time string will return a tuple of ints,
    i.e. "09:44" returns (9, 44) with the default args,
    you can pass any function to the type argument.
    """

    return map(type_of, timestring.split(":"))

def calendar_wrapper(function):
    """
    Decorator which checks if the calendar function was
    called as an ajax request or not, if so, then the
    the wrapper constructs the arguments for the call
    from the POST items
    """

    def inner(*args, **kwargs):
        """
        Checks argument length and constructs the call
        based on that.
        """

        if isinstance(args[0], WSGIRequest):
            request = args[0]
            try:
                eeid = request.POST.get('eeid', None)
                json_dict = {
                    'success': True,
                    'calendar': function(user=eeid)
                }
                return HttpResponse(simplejson.dumps(json_dict))

            except Exception as e:
                return HttpResponse(str(e))

        else:
            # if the function was called from a view
            # let it just do it's thing
            return function(*args, **kwargs)

    return inner

@calendar_wrapper
def gen_calendar(year=datetime.datetime.today().year,
                 month=datetime.datetime.today().month,
                 day=datetime.datetime.today().day,
                 user=None):

    """
    Returns a HTML calendar, calling a database user to get their day-by-day
    entries and gives each day a special CSS class so that days can be styled
    individually.

    The generated HTML should be 'pretty printed' as well, so the output code
    should be pretty readable.
    """

    # django passes us Unicode strings
    year, month, day = int(year), int(month), int(day)

    if month-1 not in MONTH_MAP.keys():
        raise Http404

    # if we've generated December, link to the next year
    if month + 1 == 13:
        next_url = '"/calendar/%s/%s"' % (year + 1, 1)
    else:
        next_url = '"/calendar/%s/%s"' % (year, month + 1)

    # if we've generated January, link to the previous year
    if month - 1 == 0:
        previous_url = '"/calendar/%s/%s"' % (year - 1, 12)
    else:
        previous_url = '"/calendar/%s/%s"' % (year, month - 1)

    # need to use authorisation and sessions to get this
    # for testing we'll just grab the same db object
    database = Tbluser.objects.get(id__exact=user)

    # pull out the entries for the given month
    try:
        database = TrackingEntry.objects.filter(
            user=database.id,
            entry_date__year=year,
            entry_date__month=month
            )

    except TrackingEntry.DoesNotExist:
        # it seems Django still follows through with the assignment
        # when it raises an error, this is actually quite good because
        # we can treat the query set like normal
        pass

    # create a semi-sparsely populated n-dimensional
    # array with the month's days per week
    calendar_array = cdr.monthcalendar(
        int(year),
        int(month)
    )

    # creating a list holder for the strings
    # this is faster than concatenating the
    # strings as we go.
    cal_html = list()
    to_cal = cal_html.append

    # create the table header
    to_cal("""
\n\t\t\t""")

    to_cal("""

                  <

                {2}

                  >

\n""".format(previous_url,
                                next_url,
                                MONTH_MAP[int(month)-1][1]
                        )
           )

    # insert day names
    to_cal("""\n\t\t\t

                Mon
                Tue
                Wed
                Thu
                Fri
                Sat
                Sun

\n""")

    # each row in the calendar_array is a week
    # in the calendar, so create a new row
    for week_ in calendar_array:
        to_cal("""\n\t\t\t
\n""")

        for _day in week_:

            # the calendar_array fills extraneous days
            # with 0's, we can catch that and treat either
            # end of the calendar differently in the CSS
            if _day != 0:
                emptyclass = 'day-class empty-day'
            else:
                emptyclass = 'empty'

            # we've got the month in the query set,
            # so just query that set for individual days
            try:
                # get all the data from our in-memory query-set.
                data = database.get(entry_date__day=_day)

                # Pass these to the page so that the jQuery functions
                # get the function arguments to edit those elements
                vals = [
                    data.start_time.hour,
                    data.start_time.minute,
                    str(data.start_time)[0:5],
                    data.end_time.hour,
                    data.end_time.minute,
                    str(data.end_time)[0:5],
                    data.entry_date,
                    data.daytype,
                    _day,
                    data.id
                    ]

                to_cal("""\t\t\t\t
                       {8}	\n""".format(*vals)
                       )

            except TrackingEntry.DoesNotExist:

                # For clicking blank days to input the day quickly into the
                # box. An alternative to the datepicker
                if _day != 0:
                    entry_date_string = '-'.join(map(pad,
                                                     [year, month, _day]
                                                     )
                                                )
                else:
                    entry_date_string = ''

                # we don't want to write a 0 in the box
                _day = '&nbsp' if _day == 0 else _day

                # write in the box and give the empty boxes a way to clear
                # the form
                to_cal("""\t\t\t\t{2}	\n""".format(
                                                  entry_date_string,
                                                  emptyclass,
                                                  _day)
                                              )

        # close up that row
        to_cal("""\t\t\t
\n""")

    # close up the table
    to_cal("""\n
""")

    # join up the html and push it back
    return ''.join(cal_html)

def json_response(func):

    """
    Decorator function that when applied to a function which
    returns some json data will be turned into a HttpResponse

    This is useful because the call site can literally just
    call the function as it is without needed to make a http-
    response.
    """

    def inner(request):

        """
        Grabs the request object on the decorated and calls
        it
        """

        return HttpResponse(simplejson.dumps(func(request)),
                            mimetype="application/javscript")
    return inner

def request_check(func):

    """
    Decorator to check an incoming request against a few rules
    """

    def inner(request):

        """
        Pulls the request object off the decorated function
        """

        if not request.is_ajax():
            raise Http404

        if not request.session.get('user_id', None):
            # if there is no user id in the session
            # something weird is going on
            raise Http404

        return func(request)

    return inner

@request_check
@json_response
def ajax_add_entry(request):

    '''
    Adds a calendar entry asynchronously
    '''

    # object to dump form data into
    form = {
        'entry_date': None,
        'start_time': None,
        'end_time': None,
        'daytype': None,
        'breaks': None
    }

    # get the form data from the request object
    form.update(get_request_data(form, request))

    # create objects to put our data into
    json_data = dict()

    try:
        # server-side time validation
        if not validate_time(form['start_time'], form['end_time']):
            json_data['error'] = "Start time after end time"
            return json_data
    except ValueError:
        json_data['error'] = "Date Error"
        return json_data

    # need to add a breaks section to the form
    form['breaks'] = "00:15:00"

    try:
        entry = TrackingEntry(**form)
        entry.save()
    except IntegrityError as error:
        if error[0] == DUPLICATE_ENTRY:
            json_data['error'] = "There is a duplicate entry for this value"
        else:
            json_data['error'] = str(error)
        return json_data

    year, month, day = map(int,
                           form['entry_date'].split("-")
                           )

    calendar = gen_calendar(year, month, day,
                            form['user_id'])

    # if all went well
    json_data['success'] = True
    json_data['calendar'] = calendar
    return json_data

@request_check
@json_response
def ajax_delete_entry(request):
    """
    Asynchronously deletes an entry
    """

    form = {
        'hidden-id': None,
        'entry_date': None
    }

    # get the form data from the request object
    form.update(get_request_data(form, request))

    # create our json structure
    json_data = dict()

    if form['hidden-id']:
        try:
            # get the user and make sure that the user
            # assigned to the TrackingEntry is the same
            # as what's requesting the deletion
            user = Tbluser.objects.get(id__exact=form['user_id'])
            entry = TrackingEntry(id=form['hidden-id'],
                                  user=user)
            entry.delete()
        except Exception as error:
            json_data['error'] = str(error)
            return json_data

    year, month, day = map(int,
                           form['entry_date'].split("-")
                           )

    calendar = gen_calendar(year, month, day,
                            user=form['user_id'])

    # if all went well
    json_data['success'] = True
    json_data['calendar'] = calendar
    return json_data

@json_response
def ajax_error(error):

    """
    Returns a HttpResponse with JSON as a payload with the error
    code as the string that the function is called with
    """

    return {
        'success': False,
        'error': error
        }

@request_check
@json_response
def ajax_change_entry(request):

    '''
    Changes a calendar entry asynchronously
    '''

    # object to dump form data into
    form = {
        'entry_date': None,
        'start_time': None,
        'end_time': None,
        'daytype': None,
        'breaks': None,
        'hidden-id': None
    }

    # get the form data from the request object
    form.update(get_request_data(form, request))

    # create objects to put our data into
    json_data = dict()

    try:
        # server-side time validation
        if not validate_time(form['start_time'], form['end_time']):
            json_data['error'] = "Start time after end time"
            return json_data
    except ValueError:
        json_data['error'] = "Date Error"
        return json_data

    # need to add a breaks section to the form
    form['breaks'] = "00:15:00"

    if form['hidden-id']:
        try:
            # get the user and make sure that the user
            # assigned to the TrackingEntry is the same
            # as what's requesting the change
            user = Tbluser.objects.get(id__exact=form['user_id'])
            entry = TrackingEntry(id=form['hidden-id'],
                                  user=user)

            # change the fields on the retrieved entry
            entry.entry_date = form['entry_date']
            entry.start_time = form['start_time']
            entry.end_time = form['end_time']
            entry.daytype = form['daytype']
            entry.breaks = form['breaks']

            entry.save()

        except Exception as error:
            json_data['error'] = str(error)
            return json_data

    year, month, day = map(int,
                           form['entry_date'].split("-")
                           )

    calendar = gen_calendar(year, month, day,
                            form['user_id'])

    # if all went well
    json_data['success'] = True
    json_data['calendar'] = calendar
    return json_data
<|endoftext|>


<commit_before>import struct

from telecommand import Telecommand

class EraseBootTableEntry(Telecommand):
    def apid(self):
        return 0xB0

    def payload(self):
        mask = 0
        for e in self._entries:
            mask |= 1 << e

        return [mask]

    def __init__(self, entries):
        self._entries = entries

class WriteProgramPart(Telecommand):
    MAX_PART_SIZE = Telecommand.MAX_PAYLOAD_SIZE - 3

    def apid(self):
        return 0xB1

    def payload(self):
        mask = 0
        for e in self._entries:
            mask |= 1 << e

        return list(struct.pack('<BI', mask, self._offset)) + list(self._content)

    def __init__(self, entries, offset, content):
        self._offset = offset
        self._content = content
        self._entries = entries

class FinalizeProgramEntry(Telecommand):
    def apid(self):
        return 0xB2

    def payload(self):
        mask = 0
        for e in self._entries:
            mask |= 1 << e

        return list(struct.pack('<BIH', mask, self._length, self._expected_crc)) + list(self._name)

    def __init__(self, entries, length, expected_crc, name):
        self._entries = entries
        self._length = length
        self._expected_crc = expected_crc
        self._name = name
<commit_msg>Fix write program telecommand part size<commit_after>import struct

from telecommand import Telecommand

class EraseBootTableEntry(Telecommand):
    def apid(self):
        return 0xB0

    def payload(self):
        mask = 0
        for e in self._entries:
            mask |= 1 << e

        return [mask]

    def __init__(self, entries):
        self._entries = entries

class WriteProgramPart(Telecommand):
    MAX_PART_SIZE = Telecommand.MAX_PAYLOAD_SIZE - 5

    def apid(self):
        return 0xB1

    def payload(self):
        mask = 0
        for e in self._entries:
            mask |= 1 << e

        return list(struct.pack('<BI', mask, self._offset)) + list(self._content)

    def __init__(self, entries, offset, content):
        self._offset = offset
        self._content = content
        self._entries = entries

class FinalizeProgramEntry(Telecommand):
    def apid(self):
        return 0xB2

    def payload(self):
        mask = 0
        for e in self._entries:
            mask |= 1 << e

        return list(struct.pack('<BIH', mask, self._length, self._expected_crc)) + list(self._name)

    def __init__(self, entries, length, expected_crc, name):
        self._entries = entries
        self._length = length
        self._expected_crc = expected_crc
        self._name = name
<|endoftext|>


<commit_before>#!/usr/bin/python
#IRC-based CNC Botnet
#Luke Matarazzo
#Jackcson Sadowski

import socket
import ftplib
import urllib2
import urllib
import sys
import ctypes
import random
import time
import platform
import os

#IRC Settings
server = "server"
channel = "#cnc"
botnick = "cncnick"

#THIS SECTION IS FOR CONNECTION TO THE SERVER
#Connecting to the IRC Server
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  #defines the socket
print "connecting to: "+server
irc.connect((server, 6667))  #connects to the server
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!\n")  #user authentication
irc.send("NICK "+ botnick +"\n")  #sets nick
irc.send("PRIVMSG nickserv :iNOOPE\r\n")  #auth
irc.send("JOIN "+ channel +"\n")  #join the channel
<commit_msg>adding initial basic structure<commit_after>#!/usr/bin/python
#IRC-based CNC Botnet
#Authors: Luke Matarazzo and Jackson Sadowski
#Blizzo

import socket
import ftplib
import urllib2
import urllib
import sys
import ctypes
import random
import time
import platform
import os

#IRC Settings
server = "server"
channel = "#cnc"
botnick = "cncnick"

def iAmHere(): #send back to IRC server that you are here
	print "'iAmHere' function not yet implemented"

def iAmGood(): #send back to IRC server that you are good
	print "'iAmGood' function not yet implemented"

#dictionary of functions
commands = {
	"are you there" : iAmHere,
	"how are you" : iAmGood
}

#function which parses the command and determine how to handle it
def parseCommand(command):
	#have to actually parse the text and find the command.
	print "in the parseCommand function"
	print "arg is '%s'" % command
	# print "calling appropriate function..."
	# commands[command]()
	# print "function called"

#THIS SECTION IS FOR CONNECTION TO THE SERVER
#Connecting to the IRC Server
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creates socket
print "connecting to: "+server
irc.connect((server, 6667)) #connects to the server
irc.send("USER "+ botnick +" "+ botnick +" "+ botnick +" :This is a fun bot!\n") #user authentication
irc.send("NICK "+ botnick +"\n") #sets nick
irc.send("PRIVMSG nickserv :iNOOPE\r\n") #auth
irc.send("JOIN "+ channel +"\n") #join the channel

#infinite loop to listen for messages aka commands
while 1:
	text=irc.recv(4096)  #receive up to 4096 bytes
	lines = text.split("\n") #split commands based on new lines

	#The two lines below are required by the IRC RFC, if you remove them the bot will time out.
	if text.find('PING') != -1: #check if 'PING' is found
		irc.send('PONG ' + text.split() [1] + '\r\n') #returns 'PONG' back to the server to prevent pinging out

	parseCommand(text) #call function to parse commands
<|endoftext|>


<commit_before>#! /usr/bin/env python
# coding=utf8

# Add module and core folders to syspath
# TODO: Is this the right way to do this?
# see http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
import sys, os
sys.path.insert(0, "core/")
sys.path.insert(0, "modules/")
sys.path.insert(0, "modules/config/")

_DEBUG = False

from BotCore import FSIBot

bot = FSIBot("##fsi", "fsiBot", "irc.freenode.org", 6667, _DEBUG)

# Add activated modules to the bot

bot.addModule("BestOfModule")
bot.addModule("FortuneModule")
bot.addModule("MensaModule")
bot.addModule("DeiMuddaModule")
bot.addModule("PastebinModule")
bot.addModule("BeerModule")
bot.addModule("RRouletteModule")

# Start :)
bot.start()
<commit_msg>Bot now uses a proper configfile<commit_after>#! /usr/bin/env python
# coding=utf8

# Add module and core folders to syspath
# TODO: Is this the right way to do this?
# see http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
import sys, os, config
sys.path.insert(0, "thirdparty/")
sys.path.insert(0, "core/")
sys.path.insert(0, "modules/")
sys.path.insert(0, "modules/config/")

from BotCore import FSIBot

# Open config file
cfg = config.Config(file("bot.config"))
botcfg = cfg.bot

bot = FSIBot(botcfg.channel, botcfg.name, botcfg.server, botcfg.port, botcfg.debug)

# Add activated modules to the bot
for mod in botcfg.modules:
    bot.addModule(mod)

# Start :)
bot.start()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from .upload_resource import UploadResource
from .download_resource import DownloadResource
from .thumbnail_resource import ThumbnailResource
from .filepath import MediaFilePaths

from twisted.web.resource import Resource

import logging

logger = logging.getLogger(__name__)

class MediaRepositoryResource(Resource):
    """Profiles file uploading and downloading.

    Uploads are POSTed to a resource which returns a token which is used to GET
    the download::

        => POST /_matrix/media/v1/upload HTTP/1.1
           Content-Type: <media-type>

           <media>

        <= HTTP/1.1 200 OK
           Content-Type: application/json

           { "token": <media-id> }

        => GET /_matrix/media/v1/download/<media-id> HTTP/1.1

        <= HTTP/1.1 200 OK
           Content-Type: <media-type>
           Content-Disposition: attachment;filename=<upload-filename>

           <media>

    Clients can get thumbnails by supplying a desired width and height and
    thumbnailing method::

        => GET /_matrix/media/v1
                /thumbnail/<media-id>?width=<w>&height=<h>&method=<m> HTTP/1.1

        <= HTTP/1.1 200 OK
           Content-Type: image/jpeg or image/png

           <thumbnail>

    The thumbnail methods are "crop" and "scale". "scale" trys to return an
    image where either the width or the height is smaller than the requested
    size. The client should then scale and letterbox the image if it needs to
    fit within a given rectangle. "crop" trys to return an image where the
    width and height are close to the requested size and the aspect matches
    the requested size. The client should scale the image if it needs to fit
    within a given rectangle.
    """

    def __init__(self, hs):
        Resource.__init__(self)
        filepaths = MediaFilePaths(hs.config.media_store_path)
        self.putChild("upload", UploadResource(hs, filepaths))
        self.putChild("download", DownloadResource(hs, filepaths))
        self.putChild("thumbnail", ThumbnailResource(hs, filepaths))
<commit_msg>Fix media repository doc string to include server_name<commit_after># -*- coding: utf-8 -*-
# Copyright 2014 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from .upload_resource import UploadResource
from .download_resource import DownloadResource
from .thumbnail_resource import ThumbnailResource
from .filepath import MediaFilePaths

from twisted.web.resource import Resource

import logging

logger = logging.getLogger(__name__)

class MediaRepositoryResource(Resource):
    """Profiles file uploading and downloading.

    Uploads are POSTed to a resource which returns a token which is used to GET
    the download::

        => POST /_matrix/media/v1/upload HTTP/1.1
           Content-Type: <media-type>

           <media>

        <= HTTP/1.1 200 OK
           Content-Type: application/json

           { "token": <media-id> }

        => GET /_matrix/media/v1/download/<server_name>/<media-id> HTTP/1.1

        <= HTTP/1.1 200 OK
           Content-Type: <media-type>
           Content-Disposition: attachment;filename=<upload-filename>

           <media>

    Clients can get thumbnails by supplying a desired width and height and
    thumbnailing method::

        => GET /_matrix/media/v1/thumbnail/<server_name>
                /<media-id>?width=<w>&height=<h>&method=<m> HTTP/1.1

        <= HTTP/1.1 200 OK
           Content-Type: image/jpeg or image/png

           <thumbnail>

    The thumbnail methods are "crop" and "scale". "scale" trys to return an
    image where either the width or the height is smaller than the requested
    size. The client should then scale and letterbox the image if it needs to
    fit within a given rectangle. "crop" trys to return an image where the
    width and height are close to the requested size and the aspect matches
    the requested size. The client should scale the image if it needs to fit
    within a given rectangle.
    """

    def __init__(self, hs):
        Resource.__init__(self)
        filepaths = MediaFilePaths(hs.config.media_store_path)
        self.putChild("upload", UploadResource(hs, filepaths))
        self.putChild("download", DownloadResource(hs, filepaths))
        self.putChild("thumbnail", ThumbnailResource(hs, filepaths))
<|endoftext|>


<commit_before># FIXME more descriptive name (as valgrind only applicable to native code)
def invoke_test(tsk):
    def print_vg_frame_component(frame, tag, prefix):
        o = frame.find(tag)
        if o != None:
            from xml.sax.saxutils import unescape
            print '    ' + prefix + ': ' + unescape(o.text)
    # invoke_test
    import subprocess
    import os
    os.environ["ABORT_ON_FAILURE"] = "1"
    os.environ["NO_ERROR_DIALOGS"] = "1"
    testfile = tsk.env.cxxprogram_PATTERN % tsk.generator.test
    testargs = tsk.generator.args
    bldpath = tsk.generator.bld.bldnode.abspath()
    testfilepath = os.path.join(bldpath, testfile)
    if not tsk.env.VALGRIND_ENABLE:
        cmdline = []
        cmdline.append(testfile)
        for arg in testargs:
            cmdline.append(arg)
        subprocess.check_call(cmdline, executable=testfilepath, cwd=bldpath)
    else:
        xmlfile = tsk.generator.test + '.xml'
        cmdline = []
        cmdline.append('--leak-check=yes')
        cmdline.append('--suppressions=../ValgrindSuppressions.txt')
        cmdline.append('--xml=yes')
        cmdline.append('--xml-file=' + xmlfile)
        cmdline.append('./' + testfile)
        for arg in testargs:
            cmdline.append(arg)
        subprocess.check_call(cmdline, executable='valgrind', cwd=bldpath)

        import xml.etree.ElementTree as ET
        doc = ET.parse(os.path.join(bldpath, xmlfile))
        errors = doc.findall('//error')
        if len(errors) > 0:
            for error in errors:
                print '---- error start ----'
                frames = error.findall('.//frame')
                for frame in frames:
                    print '  ---- frame start ----'
                    for tag, prefix in [['ip', 'Object'],
                                        ['fn', 'Function'],
                                        ['dir', 'Directory'],
                                        ['file', 'File'],
                                        ['line', 'Line'],
                                       ]:
                        print_vg_frame_component(frame, tag, prefix)
                    print '  ---- frame end ----'
                print '---- error end ----'
            raise Exception("Errors from valgrind")

def guess_dest_platform():
    # literally copied (for consistency) from default_platform.py in ohdevtools
    import platform
    if platform.system() == 'Windows':
        return 'Windows-x86'
    if platform.system() == 'Linux' and platform.architecture()[0] == '32bit' and platform.machine()[0:3] == 'ppc':
        return 'Linux-ppc32'
    if platform.system() == 'Linux' and platform.architecture()[0] == '32bit':
        return 'Linux-x86'
    if platform.system() == 'Linux' and platform.architecture()[0] == '64bit':
        return 'Linux-x64'
    if platform.system() == 'Darwin':
        # Mac behaves similarly to Windows - a 64-bit machine can support
        # both 32-bit and 64-bit processes. We prefer 32-bit because it's
        # generally more compatible and in particular Mono is 32-bit-only.
        return 'Mac-x86'
    return None

def configure_toolchain(conf):
    import os, sys
    platform_info = get_platform_info(conf.options.dest_platform)
    if platform_info['build_platform'] != sys.platform:
        conf.fatal('Can only build for {0} on {1}, but currently running on {2}.'.format(conf.options.dest_platform, platform_info['build_platform'], sys.platform))
    conf.env.MSVC_TARGETS = ['x86']
    if conf.options.dest_platform in ['Windows-x86', 'Windows-x64']:
        conf.load('msvc')
        conf.env.append_value('CXXFLAGS',['/EHsc', '/DDEFINE_TRACE', '/DDEFINE_'+platform_info['endian']+'_ENDIAN', '/D_CRT_SECURE_NO_WARNINGS'])
        if conf.options.debugmode == 'Debug':
            conf.env.append_value('CXXFLAGS',['/MTd', '/Z7', '/Od', '/RTC1', '/DDEFINE_DEBUG'])
            conf.env.append_value('LINKFLAGS', ['/debug'])
        else:
            conf.env.append_value('CXXFLAGS',['/MT', '/Ox'])
        conf.env.append_value('CFLAGS', conf.env['CXXFLAGS'])
        # Only enable warnings for C++ code as C code si typically third party and often generates many warnings
        conf.env.append_value('CXXFLAGS',['/W4', '/WX'])
    else:
        conf.load('compiler_cxx')
        conf.load('compiler_c')
        conf.env.append_value('CFLAGS', '-g')
        conf.env.append_value('CXXFLAGS', '-g')
        conf.env.append_value('CXXFLAGS', '-std=c++0x')
        conf.env.append_value('LINKFLAGS', ['-g', '-Wl,--fatal-warnings'])
        conf.env.append_value('CXXFLAGS', [
                '-pipe', '-D_GNU_SOURCE', '-D_REENTRANT', '-DDEFINE_TRACE',
                '-DDEFINE_'+platform_info['endian']+'_ENDIAN', '-fvisibility=hidden',])
        if conf.options.debugmode == 'Debug':
            conf.env.append_value('CXXFLAGS',['-O0', '-DDEFINE_DEBUG'])
        else:
            conf.env.append_value('CXXFLAGS',['-O2'])
        conf.env.append_value('CFLAGS', conf.env['CXXFLAGS'])
        # Don't enable warnings for C code as its typically third party and written to different standards
        conf.env.append_value('CXXFLAGS', [
                '-fexceptions', '-Wall', '-Werror'])

        if conf.options.dest_platform in ['Linux-x86']:
            conf.env.append_value('VALGRIND_ENABLE', ['1'])
        if conf.options.dest_platform in ['Linux-x86', 'Linux-x64', 'Linux-ARM', 'Linux-ppc32']:
            conf.env.append_value('LINKFLAGS', ['-pthread'])
            conf.env.append_value('CXXFLAGS',['-Wno-psabi', '-fPIC'])
        elif conf.options.dest_platform in ['Mac-x86', 'Mac-x64']:
            conf.env.append_value('LINKFLAGS', ['-pthread'])
            if conf.options.dest_platform == 'Mac-x86':
                conf.env.append_value('CXXFLAGS', ['-arch', 'i386'])
                conf.env.append_value('LINKFLAGS', ['-arch', 'i386'])
            if conf.options.dest_platform == 'Mac-x64':
                conf.env.append_value('CXXFLAGS', ['-arch', 'x86_64'])
                conf.env.append_value('LINKFLAGS', ['-arch', 'x86_64'])
            conf.env.append_value('CXXFLAGS',['-fPIC', '-mmacosx-version-min=10.4', '-DPLATFORM_MACOSX_GNU'])
            conf.env.append_value('LINKFLAGS',['-framework', 'CoreFoundation', '-framework', 'SystemConfiguration'])
        # Options for Core-ppc32 and Core-armv6
        if conf.options.dest_platform in ['Core-ppc32', 'Core-armv6']:

            platform = conf.options.dest_platform

            if platform == 'Core-ppc32':
                default_cross = '/opt/rtems-4.11/bin/powerpc-rtems4.11-'
                cpu = '403'
            if platform == 'Core-armv6':
                default_cross = '/opt/rtems-4.11/bin/arm-rtemseabi4.11-'
                cpu = 'arm926ej-s'
                # core2 is arm based - pass no-psabi flag to avoid excessive noise during compilation.
                conf.env.append_value('CXXFLAGS', ['-Wno-psabi'])
                conf.env.append_value('CFLAGS',   ['-Wno-psabi'])

            if conf.options.cross == None:
                conf.options.cross = default_cross

            try:
                linkflags = os.environ['CROSS_LINKFLAGS'].split()
            except KeyError:
                # This is a bit pants - we should configure wag with libosa/libplatform paths,
                # and use that path here.
                linkflags = [   '-B', '../dependencies/' + platform + '/libplatform/lib/',
                                '-B', '../dependencies/' + platform + '/libosa/lib/',
                                '../dependencies/' + platform + '/libplatform/lib/FileOpen.o',
                                '-specs', 'bsp_specs',
                                '-lplatform']

            conf.env.append_value('LINKFLAGS', linkflags)
            conf.env.append_value('LINKFLAGS',  ['-mcpu=' + cpu])
            conf.env.append_value('CXXFLAGS',  ['-mcpu=' + cpu])
            conf.env.append_value('CFLAGS',    ['-mcpu=' + cpu])
            conf.env.append_value('DEFINES',   ['BYTE_ORDER=' + platform_info['endian'] + '_ENDIAN'])

    if conf.options.cross or os.environ.get('CROSS_COMPILE', None):
        cross_compile = conf.options.cross or os.environ['CROSS_COMPILE']
        conf.msg('Cross compiling using compiler prefix:', cross_compile)
        conf.env.CC = cross_compile + 'gcc'
        conf.env.CXX = cross_compile + 'g++'
        conf.env.AR = cross_compile + 'ar'
        conf.env.LINK_CXX = cross_compile + 'g++'
        conf.env.LINK_CC = cross_compile + 'gcc'

# helper functions for guess_xxx_location
def set_env_verbose(conf, varname, value):
    conf.msg(
        'Setting %s to' % varname,
        'True' if value is True else
        'False' if value is False else
        value)
    setattr(conf.env, varname, value)
    return value
def match_path(conf, paths, message):
    import os.path
    for p in paths:
        fname = p.format(
            options=conf.options,
            debugmode_lc=conf.options.debugmode.lower(),
            debugmode_tc=conf.options.debugmode.title(),
            platform_info=get_platform_info(conf.options.dest_platform))
        if os.path.exists(fname):
            return os.path.abspath(fname)
    conf.fatal(message)

def guess_ohnet_location(conf):
    set_env_verbose(conf, 'INCLUDES_OHNET', match_path(
        conf,
        [
            '{options.ohnet_include_dir}',
            '{options.ohnet}/Build/Include',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_lc}-dev/include/ohnet',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/include/ohnet',
        ],
        message='Specify --ohnet-include-dir or --ohnet')
    )
    set_env_verbose(conf, 'STLIBPATH_OHNET', match_path(
        conf,
        [
            '{options.ohnet_lib_dir}',
            '{options.ohnet}/Build/Obj/{platform_info[ohnet_plat_dir]}/{options.debugmode}',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_lc}-dev/lib',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/lib',
        ],
        message='Specify --ohnet-lib-dir or --ohnet')
    )
    set_env_verbose(conf, 'TEXT_TRANSFORM_PATH', match_path(
        conf,
        [
            '{options.ohnet}/Build/Tools',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/lib/t4',
        ],
        message='Specify --ohnet')
    )
    set_env_verbose(conf, 'T4_TEMPLATE_PATH', match_path(
        conf,
        [
            '{options.ohnet}/OpenHome/Net/T4/Templates',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/lib/t4',
        ],
        message='Specify --ohnet')
    )

def guess_ohmediaplayer_location(conf):
    set_env_verbose(conf, 'INCLUDES_OHMEDIAPLAYER', match_path(
        conf,
        [
            '{options.ohmediaplayer_include_dir}',
            '{options.ohmediaplayer}',
            'dependencies/{options.dest_platform}/ohMediaPlayer/include',
        ],
        message='Specify --ohmediaplayer-include-dir or --ohmediaplayer')
    )
    set_env_verbose(conf, 'STLIBPATH_OHMEDIAPLAYER', match_path(
        conf,
        [
            '{options.ohmediaplayer_lib_dir}',
            '{options.ohmediaplayer}/build',
            'dependencies/{options.dest_platform}/ohMediaPlayer/lib',
        ],
        message='Specify --ohmediaplayer-lib-dir or --ohmediaplayer')
    )

def get_platform_info(dest_platform):
    platforms = {
        'Linux-x86': dict(endian='LITTLE',   build_platform='linux2', ohnet_plat_dir='Posix'),
        'Linux-x64': dict(endian='LITTLE',   build_platform='linux2', ohnet_plat_dir='Posix'),
        'Linux-ARM': dict(endian='LITTLE',   build_platform='linux2', ohnet_plat_dir='Posix'),
        'Linux-ppc32': dict(endian='BIG',    build_platform='linux2', ohnet_plat_dir='Posix'),
        'Windows-x86': dict(endian='LITTLE', build_platform='win32',  ohnet_plat_dir='Windows'),
        'Windows-x64': dict(endian='LITTLE', build_platform='win32',  ohnet_plat_dir='Windows'),
        'Core-ppc32': dict(endian='BIG',     build_platform='linux2', ohnet_plat_dir='Core-ppc32'),
        'Core-armv6': dict(endian='LITTLE',  build_platform='linux2', ohnet_plat_dir='Core-armv6'),
        'Mac-x86': dict(endian='LITTLE',     build_platform='darwin', ohnet_plat_dir='Mac-x86'),
        'Mac-x64': dict(endian='LITTLE',     build_platform='darwin', ohnet_plat_dir='Mac-x64'),
        'iOs-ARM': dict(endian='LITTLE',     build_platform='darwin', ohnet_plat_dir='Mac/arm'),
    }
    return platforms[dest_platform]
<commit_msg>Add Core-armv5 support.<commit_after># FIXME more descriptive name (as valgrind only applicable to native code)
def invoke_test(tsk):
    def print_vg_frame_component(frame, tag, prefix):
        o = frame.find(tag)
        if o != None:
            from xml.sax.saxutils import unescape
            print '    ' + prefix + ': ' + unescape(o.text)
    # invoke_test
    import subprocess
    import os
    os.environ["ABORT_ON_FAILURE"] = "1"
    os.environ["NO_ERROR_DIALOGS"] = "1"
    testfile = tsk.env.cxxprogram_PATTERN % tsk.generator.test
    testargs = tsk.generator.args
    bldpath = tsk.generator.bld.bldnode.abspath()
    testfilepath = os.path.join(bldpath, testfile)
    if not tsk.env.VALGRIND_ENABLE:
        cmdline = []
        cmdline.append(testfile)
        for arg in testargs:
            cmdline.append(arg)
        subprocess.check_call(cmdline, executable=testfilepath, cwd=bldpath)
    else:
        xmlfile = tsk.generator.test + '.xml'
        cmdline = []
        cmdline.append('--leak-check=yes')
        cmdline.append('--suppressions=../ValgrindSuppressions.txt')
        cmdline.append('--xml=yes')
        cmdline.append('--xml-file=' + xmlfile)
        cmdline.append('./' + testfile)
        for arg in testargs:
            cmdline.append(arg)
        subprocess.check_call(cmdline, executable='valgrind', cwd=bldpath)

        import xml.etree.ElementTree as ET
        doc = ET.parse(os.path.join(bldpath, xmlfile))
        errors = doc.findall('//error')
        if len(errors) > 0:
            for error in errors:
                print '---- error start ----'
                frames = error.findall('.//frame')
                for frame in frames:
                    print '  ---- frame start ----'
                    for tag, prefix in [['ip', 'Object'],
                                        ['fn', 'Function'],
                                        ['dir', 'Directory'],
                                        ['file', 'File'],
                                        ['line', 'Line'],
                                       ]:
                        print_vg_frame_component(frame, tag, prefix)
                    print '  ---- frame end ----'
                print '---- error end ----'
            raise Exception("Errors from valgrind")

def guess_dest_platform():
    # literally copied (for consistency) from default_platform.py in ohdevtools
    import platform
    if platform.system() == 'Windows':
        return 'Windows-x86'
    if platform.system() == 'Linux' and platform.architecture()[0] == '32bit' and platform.machine()[0:3] == 'ppc':
        return 'Linux-ppc32'
    if platform.system() == 'Linux' and platform.architecture()[0] == '32bit':
        return 'Linux-x86'
    if platform.system() == 'Linux' and platform.architecture()[0] == '64bit':
        return 'Linux-x64'
    if platform.system() == 'Darwin':
        # Mac behaves similarly to Windows - a 64-bit machine can support
        # both 32-bit and 64-bit processes. We prefer 32-bit because it's
        # generally more compatible and in particular Mono is 32-bit-only.
        return 'Mac-x86'
    return None

def configure_toolchain(conf):
    import os, sys
    platform_info = get_platform_info(conf.options.dest_platform)
    if platform_info['build_platform'] != sys.platform:
        conf.fatal('Can only build for {0} on {1}, but currently running on {2}.'.format(conf.options.dest_platform, platform_info['build_platform'], sys.platform))
    conf.env.MSVC_TARGETS = ['x86']
    if conf.options.dest_platform in ['Windows-x86', 'Windows-x64']:
        conf.load('msvc')
        conf.env.append_value('CXXFLAGS',['/EHsc', '/DDEFINE_TRACE', '/DDEFINE_'+platform_info['endian']+'_ENDIAN', '/D_CRT_SECURE_NO_WARNINGS'])
        if conf.options.debugmode == 'Debug':
            conf.env.append_value('CXXFLAGS',['/MTd', '/Z7', '/Od', '/RTC1', '/DDEFINE_DEBUG'])
            conf.env.append_value('LINKFLAGS', ['/debug'])
        else:
            conf.env.append_value('CXXFLAGS',['/MT', '/Ox'])
        conf.env.append_value('CFLAGS', conf.env['CXXFLAGS'])
        # Only enable warnings for C++ code as C code si typically third party and often generates many warnings
        conf.env.append_value('CXXFLAGS',['/W4', '/WX'])
    else:
        conf.load('compiler_cxx')
        conf.load('compiler_c')
        conf.env.append_value('CFLAGS', '-g')
        conf.env.append_value('CXXFLAGS', '-g')
        conf.env.append_value('CXXFLAGS', '-std=c++0x')
        conf.env.append_value('LINKFLAGS', ['-g', '-Wl,--fatal-warnings'])
        conf.env.append_value('CXXFLAGS', [
                '-pipe', '-D_GNU_SOURCE', '-D_REENTRANT', '-DDEFINE_TRACE',
                '-DDEFINE_'+platform_info['endian']+'_ENDIAN', '-fvisibility=hidden',])
        if conf.options.debugmode == 'Debug':
            conf.env.append_value('CXXFLAGS',['-O0', '-DDEFINE_DEBUG'])
        else:
            conf.env.append_value('CXXFLAGS',['-O2'])
        conf.env.append_value('CFLAGS', conf.env['CXXFLAGS'])
        # Don't enable warnings for C code as its typically third party and written to different standards
        conf.env.append_value('CXXFLAGS', [
                '-fexceptions', '-Wall', '-Werror'])

        if conf.options.dest_platform in ['Linux-x86']:
            conf.env.append_value('VALGRIND_ENABLE', ['1'])
        if conf.options.dest_platform in ['Linux-x86', 'Linux-x64', 'Linux-ARM', 'Linux-ppc32']:
            conf.env.append_value('LINKFLAGS', ['-pthread'])
            conf.env.append_value('CXXFLAGS',['-Wno-psabi', '-fPIC'])
        elif conf.options.dest_platform in ['Mac-x86', 'Mac-x64']:
            conf.env.append_value('LINKFLAGS', ['-pthread'])
            if conf.options.dest_platform == 'Mac-x86':
                conf.env.append_value('CXXFLAGS', ['-arch', 'i386'])
                conf.env.append_value('LINKFLAGS', ['-arch', 'i386'])
            if conf.options.dest_platform == 'Mac-x64':
                conf.env.append_value('CXXFLAGS', ['-arch', 'x86_64'])
                conf.env.append_value('LINKFLAGS', ['-arch', 'x86_64'])
            conf.env.append_value('CXXFLAGS',['-fPIC', '-mmacosx-version-min=10.4', '-DPLATFORM_MACOSX_GNU'])
            conf.env.append_value('LINKFLAGS',['-framework', 'CoreFoundation', '-framework', 'SystemConfiguration'])
        # Options for Core-ppc32 and Core-armv5 / Core-armv6
        if conf.options.dest_platform in ['Core-ppc32', 'Core-armv5', 'Core-armv6']:

            platform = conf.options.dest_platform

            if platform == 'Core-ppc32':
                default_cross = '/opt/rtems-4.11/bin/powerpc-rtems4.11-'
                cpu = '403'
            if platform == 'Core-armv5':
                default_cross = '/opt/rtems-4.11/bin/arm-rtemseabi4.11-'
                cpu = 'arm926ej-s'
                # core2 is arm based - pass no-psabi flag to avoid excessive noise during compilation.
                flags = ['-Wno-psabi', '-marm', '-mapcs', '-fno-omit-frame-pointer']
                conf.env.append_value('CFLAGS', flags )
                conf.env.append_value('CXXFLAGS', flags )
            if platform == 'Core-armv6':
                default_cross = '/opt/rtems-4.11/bin/arm-rtemseabi4.11-'
                cpu = 'arm926ej-s'
                # core2 is arm based - pass no-psabi flag to avoid excessive noise during compilation.
                conf.env.append_value('CXXFLAGS', ['-Wno-psabi'])
                conf.env.append_value('CFLAGS',   ['-Wno-psabi'])

            if conf.options.cross == None:
                conf.options.cross = default_cross

            try:
                linkflags = os.environ['CROSS_LINKFLAGS'].split()
            except KeyError:
                # This is a bit pants - we should configure wag with libosa/libplatform paths,
                # and use that path here.
                linkflags = [   '-B', '../dependencies/' + platform + '/libplatform/lib/',
                                '-B', '../dependencies/' + platform + '/libosa/lib/',
                                '../dependencies/' + platform + '/libplatform/lib/FileOpen.o',
                                '-specs', 'bsp_specs',
                                '-lplatform']

            conf.env.append_value('LINKFLAGS', linkflags)
            conf.env.append_value('LINKFLAGS',  ['-mcpu=' + cpu])
            conf.env.append_value('CXXFLAGS',  ['-mcpu=' + cpu])
            conf.env.append_value('CFLAGS',    ['-mcpu=' + cpu])
            conf.env.append_value('DEFINES',   ['BYTE_ORDER=' + platform_info['endian'] + '_ENDIAN'])

    if conf.options.cross or os.environ.get('CROSS_COMPILE', None):
        cross_compile = conf.options.cross or os.environ['CROSS_COMPILE']
        conf.msg('Cross compiling using compiler prefix:', cross_compile)
        conf.env.CC = cross_compile + 'gcc'
        conf.env.CXX = cross_compile + 'g++'
        conf.env.AR = cross_compile + 'ar'
        conf.env.LINK_CXX = cross_compile + 'g++'
        conf.env.LINK_CC = cross_compile + 'gcc'

# helper functions for guess_xxx_location
def set_env_verbose(conf, varname, value):
    conf.msg(
        'Setting %s to' % varname,
        'True' if value is True else
        'False' if value is False else
        value)
    setattr(conf.env, varname, value)
    return value
def match_path(conf, paths, message):
    import os.path
    for p in paths:
        fname = p.format(
            options=conf.options,
            debugmode_lc=conf.options.debugmode.lower(),
            debugmode_tc=conf.options.debugmode.title(),
            platform_info=get_platform_info(conf.options.dest_platform))
        if os.path.exists(fname):
            return os.path.abspath(fname)
    conf.fatal(message)

def guess_ohnet_location(conf):
    set_env_verbose(conf, 'INCLUDES_OHNET', match_path(
        conf,
        [
            '{options.ohnet_include_dir}',
            '{options.ohnet}/Build/Include',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_lc}-dev/include/ohnet',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/include/ohnet',
        ],
        message='Specify --ohnet-include-dir or --ohnet')
    )
    set_env_verbose(conf, 'STLIBPATH_OHNET', match_path(
        conf,
        [
            '{options.ohnet_lib_dir}',
            '{options.ohnet}/Build/Obj/{platform_info[ohnet_plat_dir]}/{options.debugmode}',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_lc}-dev/lib',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/lib',
        ],
        message='Specify --ohnet-lib-dir or --ohnet')
    )
    set_env_verbose(conf, 'TEXT_TRANSFORM_PATH', match_path(
        conf,
        [
            '{options.ohnet}/Build/Tools',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/lib/t4',
        ],
        message='Specify --ohnet')
    )
    set_env_verbose(conf, 'T4_TEMPLATE_PATH', match_path(
        conf,
        [
            '{options.ohnet}/OpenHome/Net/T4/Templates',
            'dependencies/{options.dest_platform}/ohNet-{options.dest_platform}-{debugmode_tc}/lib/t4',
        ],
        message='Specify --ohnet')
    )

def guess_ohmediaplayer_location(conf):
    set_env_verbose(conf, 'INCLUDES_OHMEDIAPLAYER', match_path(
        conf,
        [
            '{options.ohmediaplayer_include_dir}',
            '{options.ohmediaplayer}',
            'dependencies/{options.dest_platform}/ohMediaPlayer/include',
        ],
        message='Specify --ohmediaplayer-include-dir or --ohmediaplayer')
    )
    set_env_verbose(conf, 'STLIBPATH_OHMEDIAPLAYER', match_path(
        conf,
        [
            '{options.ohmediaplayer_lib_dir}',
            '{options.ohmediaplayer}/build',
            'dependencies/{options.dest_platform}/ohMediaPlayer/lib',
        ],
        message='Specify --ohmediaplayer-lib-dir or --ohmediaplayer')
    )

def get_platform_info(dest_platform):
    platforms = {
        'Linux-x86': dict(endian='LITTLE',   build_platform='linux2', ohnet_plat_dir='Posix'),
        'Linux-x64': dict(endian='LITTLE',   build_platform='linux2', ohnet_plat_dir='Posix'),
        'Linux-ARM': dict(endian='LITTLE',   build_platform='linux2', ohnet_plat_dir='Posix'),
        'Linux-ppc32': dict(endian='BIG',    build_platform='linux2', ohnet_plat_dir='Posix'),
        'Windows-x86': dict(endian='LITTLE', build_platform='win32',  ohnet_plat_dir='Windows'),
        'Windows-x64': dict(endian='LITTLE', build_platform='win32',  ohnet_plat_dir='Windows'),
        'Core-ppc32': dict(endian='BIG',     build_platform='linux2', ohnet_plat_dir='Core-ppc32'),
        'Core-armv5': dict(endian='LITTLE',  build_platform='linux2', ohnet_plat_dir='Core-armv5'),
        'Core-armv6': dict(endian='LITTLE',  build_platform='linux2', ohnet_plat_dir='Core-armv6'),
        'Mac-x86': dict(endian='LITTLE',     build_platform='darwin', ohnet_plat_dir='Mac-x86'),
        'Mac-x64': dict(endian='LITTLE',     build_platform='darwin', ohnet_plat_dir='Mac-x64'),
        'iOs-ARM': dict(endian='LITTLE',     build_platform='darwin', ohnet_plat_dir='Mac/arm'),
    }
    return platforms[dest_platform]
<|endoftext|>


<commit_before>import requests
import misc

#misc.py - personal info
#token = '*****'
#login = '*****'
#psw = '*******'
#routerIp = 'http://192.168.1.1'
#mac ='********'
#statusUrl = routerIp + '/userRpm/StatusRpm.htm'
#DisconnectUrl = routerIp + '/userRpm/StatusRpm.htm?Disconnect=Disconnect&wan=1'
#ConnectUrl = routerIp + '/userRpm/StatusRpm.htm?Connect=Connect&wan=1'

from time import sleep
import os
import sys
from datetime import datetime, date, time

if not os.getegid() == 0:
    sys.exit('Script must be run as root')

from pyA20.gpio import gpio
from pyA20.gpio import port

global led
led = port.PA8

global led_state
led_state  = 0

global last_update_id
last_update_id = 0

global button
button = port.PA7

global button_state
button_state = 0

gpio.init()
gpio.setcfg(led, gpio.OUTPUT)
gpio.setcfg(button, gpio.INPUT)

#https://api.telegram.org/bot + token + / + method
token = misc.token
global domen
domen = 'https://api.telegram.org/bot' + token + '/'

def get_updates():
	url = domen + 'getupdates'
	r = requests.get(url)
	return r.json()

def get_message():
	#получение запроса в телеграмм
	data = get_updates()
	#ожидание ответа telegram, проверяем на OK
	if data['ok'] == True:
		#проверка - если в телеграме есть запрос
		if len(data['result']) > 0:
			#берем последний запрос
			last_object = data['result'][-1]
			#проверяем, обрабатывали ли уже этот запрос (не повторяется
			#ли)
			current_update_id = last_object['update_id']
			global last_update_id
			if last_update_id != current_update_id:
				last_update_id = current_update_id
				chat_id = last_object['message']['chat']['id']
				message_text = last_object['message']['text']
				message = {'chat_id':chat_id, 'text':message_text}
				return message
			return None
	return None

def send_message(chat_id, text = 'Wait a second, please...'):
	global domen
	url = domen + 'sendmessage?chat_id={}&text={}'.format(chat_id, text)
	requests.get(url)

def get_ip():
	#url = "https://yandex.ru/internet/"
	#result = requests.get(url)
	#if result.status_code == 200:
	#	html = result.content
	#	soup = BeautifulSoup(html, 'html.parser')
	#	ip= soup.find("li", attrs={"class": "client__item client__item_type_ipv4"}).find('div').text
	#	return ip
	#return None
	with requests.Session() as sess:
		r= sess.get(misc.statusUrl, auth=(misc.login, misc.psw))
		if r.status_code==200:
			s = r.text
			posMac= s.find(misc.mac)
			posstartIp = posMac+21
			posEndIp = s.find("\"",posstartIp, posstartIp+16)
			return s[posstartIp:posEndIp:1]

def changeIp():

	requests.get(misc.DisconnectUrl, auth=(misc.login, misc.psw))
	sleep(6)
	requests.get(misc.ConnectUrl, auth=(misc.login, misc.psw))
	sleep(6)

def change_led_state():
	try:
		global led_state
		led_state = not led_state
		gpio.output(led, led_state)
	except:
		pass

def get_button_state():
	try:
		global button
		global button_state
		button_state = gpio.input(button)
		return button_state
	except:
		pass
		return None

def main ():
	# with open('updates.json','w') as file:
	# 	json.dump(d, file, inswnt =2, ensure_ascii = False)
	print ('Bot is started')
	global button_state
	last_button_state=0
	chat_id = int(0)
	while chat_id == int(0):
		answer=get_message()
		if answer is not None:
			chat_id = answer['chat_id']
			print(chat_id)

	while True:
		answer = get_message()
		if answer is not None:
			text = answer['text']
			if text == '/getip':
				server_ip = get_ip()
				if server_ip is not None:
					send_message(chat_id, server_ip)
			if text == '/led':
				change_led_state()

			if text == '/changeip':
				changeIp()

		get_button_state()
		if button_state != None and button_state != last_button_state:
			send_message(chat_id, str(button_state))
			last_button_state = button_state
			print(str(button_state))

		#with open('bot.log', 'at') as f:
		#	text = print(datetime.now())
		#	f.write(str(text) + '\n')
		sleep(10)

if __name__ == "__main__":
	main()
<commit_msg>Fix chat_id problem<commit_after>import requests
import misc
#import json

#misc.py - personal info
#token = '*****'
#login = '*****'
#psw = '*******'
#routerIp = 'http://192.168.1.1'
#mac ='********'
#statusUrl = routerIp + '/userRpm/StatusRpm.htm'
#DisconnectUrl = routerIp + '/userRpm/StatusRpm.htm?Disconnect=Disconnect&wan=1'
#ConnectUrl = routerIp + '/userRpm/StatusRpm.htm?Connect=Connect&wan=1'

from time import sleep
import os
import sys
from datetime import datetime, date, time

if not os.getegid() == 0:
    sys.exit('Script must be run as root')

from pyA20.gpio import gpio
from pyA20.gpio import port

global led
led = port.PA8

global led_state
led_state  = 0

global last_update_id
last_update_id = 0

global button
button = port.PA7

global button_state
button_state = 0

gpio.init()
gpio.setcfg(led, gpio.OUTPUT)
gpio.setcfg(button, gpio.INPUT)

#https://api.telegram.org/bot + token + / + method
token = misc.token
global domen
domen = 'https://api.telegram.org/bot' + token + '/'

def get_updates():
	url = domen + 'getupdates'
	r = requests.get(url)
	return r.json()

def get_message():
	#получение запроса в телеграмм
	data = get_updates()
	#ожидание ответа telegram, проверяем на OK
	if data['ok'] == True:
		#проверка - если в телеграме есть запрос
		if len(data['result']) >0:
			#берем последний запрос
			last_object = data['result'][-1]
			#проверяем, обрабатывали ли уже этот запрос (не повторяется
			#ли)
			current_update_id = last_object['update_id']
			global last_update_id
			if last_update_id != current_update_id:
				last_update_id = current_update_id
				message_text = last_object['message']['text']
				chat_id = last_object['message']['chat']['id']
				message = {'chat_id':chat_id, 'text':message_text}
				return message
			return None
	return None

def send_message(chat_id, text = 'Wait a second, please...'):
	global domen
	url = domen + 'sendmessage?chat_id={}&text={}'.format(chat_id, text)
	requests.get(url)

def get_ip():
	#url = "https://yandex.ru/internet/"
	#result = requests.get(url)
	#if result.status_code == 200:
	#	html = result.content
	#	soup = BeautifulSoup(html, 'html.parser')
	#	ip= soup.find("li", attrs={"class": "client__item client__item_type_ipv4"}).find('div').text
	#	return ip
	#return None
	with requests.Session() as sess:
		r= sess.get(misc.statusUrl, auth=(misc.login, misc.psw))
		if r.status_code==200:
			s = r.text
			posMac= s.find(misc.mac)
			posstartIp = posMac+21
			posEndIp = s.find("\"",posstartIp, posstartIp+16)
			return s[posstartIp:posEndIp:1]

def changeIp():

	requests.get(misc.DisconnectUrl, auth=(misc.login, misc.psw))
	sleep(6)
	requests.get(misc.ConnectUrl, auth=(misc.login, misc.psw))
	sleep(6)

def change_led_state():
	try:
		global led_state
		led_state = not led_state
		gpio.output(led, led_state)
	except:
		pass

def get_button_state():
	try:
		global button
		global button_state
		button_state = gpio.input(button)
		return button_state
	except:
		pass
		return None

def main ():
	# with open('updates.json','w') as file:
	# 	json.dump(d, file, inswnt =2, ensure_ascii = False)
	print ('Bot is started')
	global button_state
	last_button_state=0

	while True:
		answer = get_message()
		if answer is not None:
			chat_id = answer['chat_id']
			text = answer['text']
			if text == '/getip':
				server_ip = get_ip()
				if server_ip is not None:
					send_message(chat_id, server_ip)
			if text == '/led':
				change_led_state()

			if text == '/changeip':
				changeIp()

		get_button_state()
		if button_state != None and button_state != last_button_state:
			send_message(chat_id, str(button_state))
			last_button_state = button_state
			print(str(button_state))

		#with open('bot.log', 'at') as f:
		#	text = print(datetime.now())
		#	f.write(str(text) + '\n')
		sleep(10)

if __name__ == "__main__":
	main()
<|endoftext|>


<commit_before>from dictionary_builder import dictionary_builder
import os

def validate_dictionary_substring_rules():
    appended_vals = ""

    # Get rid of keys from encoder_dictionary.
    # Append all values as "one big string"
    encoder_dict = dictionary_builder("english")
    for v in encoder_dict.values():
        appended_vals += v

    # Find length of all values appended together
    vals_len = len(appended_vals)

    # For each value-v in encoder_dictionary check that "one big string" of all values does not have more than 1 occurrence of v
    # Length_of_one_big_string_of_all_values_in_dictionary == length_of_value-v + length_of_string_found_after_replace-all_of_v_from_one_big_string
    repeated_substrings = []
    for v in encoder_dict.values():
        removed_sub_str = appended_vals.replace(v,"")
        if(len(removed_sub_str)+len(v) == vals_len): # Value v is not present as substring in any other values used.
            continue
        else:
            repeated_substrings.append(v)

    # repeated_substrings contains all the strings which are present as substrings inside other values
    print(str(repeated_substrings) + " are present inside another value in your dictionary")

def getValueAsString(d):
    appended_vals = ""
    #d is a dict
    for v in d.values():
        appended_vals += v
    return appended_vals

# Find language based on encoded string provided by the user
def findLanguage(encoded_str):
    foundFlag = False

    # Get all languages from .txt files from current directory
    languages = [str(f).replace("_dictionary.txt","") for f in os.listdir() if f.endswith(".txt")]

    # For each file do ->
    for lang in languages:
        # get all the values used for encoding
        values = dictionary_builder(lang).values()

        # use a window whose size increases from 1 to length-of-encoded-string
        # at each window-size check if the word exists in dictionary's values
        windowSize = 1
        while(windowSize <= len(encoded_str)):
            word = encoded_str[0:windowSize]
            if word in values:
                foundFlag = True
                break;
            windowSize += 1
        if foundFlag:
            print("Language = " + lang)
            return lang
    return None
<commit_msg>beautification<commit_after>from dictionary_builder import dictionary_builder
import os
import sys

def validate_dictionary_substring_rules(lang):

    # Get rid of keys from encoder_dictionary.
    # Append all values as "one big string"
    dictionary = dictionary_builder(lang)
    appended_vals = getValueAsString(dictionary)

    # Find length of all values appended together
    vals_len = len(appended_vals)

    # For each value-v in encoder_dictionary check that "one big string" of all values does not have more than 1 occurrence of v
    # Length_of_one_big_string_of_all_values_in_dictionary == length_of_value-v + length_of_string_found_after_replace-all_of_v_from_one_big_string
    repeated_substrings = []
    for v in dictionary.values():
        removed_sub_str = appended_vals.replace(v,"")
        if(len(removed_sub_str)+len(v) == vals_len): # Value v is not present as substring in any other values used.
            continue
        else:
            repeated_substrings.append(v)

    # repeated_substrings contains all the strings which are present as substrings inside other values
    print(str(repeated_substrings) + " are present inside another value in your dictionary")

def getValueAsString(d):
    appended_vals = ""
    #d is a dict
    for v in d.values():
        appended_vals += v
    return appended_vals

# Find language based on encoded string provided by the user
def findLanguage(encoded_str):
    foundFlag = False

    # Get all languages from .txt files from current directory
    languages = [str(f).replace("_dictionary.txt","") for f in os.listdir() if f.endswith(".txt")]

    # For each file do ->
    for lang in languages:
        # get all the values used for encoding
        values = dictionary_builder(lang).values()

        # use a window whose size increases from 1 to length-of-encoded-string
        # at each window-size check if the word exists in dictionary's values
        windowSize = 1
        while(windowSize <= len(encoded_str)):
            word = encoded_str[0:windowSize]
            if word in values:
                foundFlag = True
                break;
            windowSize += 1
        if foundFlag:
            print("Language = " + lang)
            return lang

    return None

    print("Did not find a language to decode this")
    return None

if __name__ == "__main__":
    validate_dictionary_substring_rules(sys.argv[1])

<|endoftext|>


<commit_before>import discord

from modules.units import *
from modules.roles import *
from modules.help import *
from modules.status import *
from modules.redditposts import *
from modules.karma import *
from modules.info import *
from modules.deco.deco import *

from modules.botModule import *

client = discord.Client()

bot_version = '1.0.0'

BotModule.loaded_modules = [Units(), Roles(), Help(), Status(bot_version), Karma(), Info(), Deco()]  # Reddit module removed as it prevented startup

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    for bot_module in BotModule.loaded_modules:
        if message.content.startswith(bot_module.trigger_char + bot_module.trigger_string):
            await bot_module.parse_command(message, client)
    for bot_module in BotModule.loaded_modules:
        if bot_module.trigger_on_mention and message.mentions:
            await bot_module.on_mention(message, client)

@client.event
async def on_reaction_add(reaction, user):
    if user == client.user:
        return
    for bot_module in BotModule.loaded_modules:
        if bot_module.listen_for_reaction:
            await bot_module.on_reaction_add(reaction, client, user)

@client.event
async def on_reaction_remove(reaction, user):
    if user == client.user:
        return
    for bot_module in BotModule.loaded_modules:
        if bot_module.listen_for_reaction:
            await bot_module.on_reaction_remove(reaction, client, user)

@client.event
async def on_ready():
    print('Login success. Your details:')
    print('User:', client.user.name)
    print('ID', client.user.id)
    print('----------')

print('scubot v' + bot_version)
try:
    tokenFile = open('token')
except FileNotFoundError:
    print('Token not found. Please make sure you have a token file in this directory.'
          ' Refer to README.md for details on getting a token.')
    quit()
print('Token found. Logging in...')
token = tokenFile.read().replace('\n', '')

for bot_module in BotModule.loaded_modules:
    if bot_module.has_background_loop:
        client.loop.create_task(bot_module.background_loop(client))

client.run(token)
<commit_msg>Fix check again<commit_after>import discord

from modules.units import *
from modules.roles import *
from modules.help import *
from modules.status import *
from modules.redditposts import *
from modules.karma import *
from modules.info import *
from modules.deco.deco import *

from modules.botModule import *

client = discord.Client()

bot_version = '1.0.0'

BotModule.loaded_modules = [Units(), Roles(), Help(), Status(bot_version), Karma(), Info(), Deco()]  # Reddit module removed as it prevented startup

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    for bot_module in BotModule.loaded_modules:
        if message.content.startswith(bot_module.trigger_char + bot_module.trigger_string):
            await bot_module.parse_command(message, client)
    for bot_module in BotModule.loaded_modules:
        if bot_module.trigger_on_mention and len(message.mentions) > 0:
            await bot_module.on_mention(message, client)

@client.event
async def on_reaction_add(reaction, user):
    if user == client.user:
        return
    for bot_module in BotModule.loaded_modules:
        if bot_module.listen_for_reaction:
            await bot_module.on_reaction_add(reaction, client, user)

@client.event
async def on_reaction_remove(reaction, user):
    if user == client.user:
        return
    for bot_module in BotModule.loaded_modules:
        if bot_module.listen_for_reaction:
            await bot_module.on_reaction_remove(reaction, client, user)

@client.event
async def on_ready():
    print('Login success. Your details:')
    print('User:', client.user.name)
    print('ID', client.user.id)
    print('----------')

print('scubot v' + bot_version)
try:
    tokenFile = open('token')
except FileNotFoundError:
    print('Token not found. Please make sure you have a token file in this directory.'
          ' Refer to README.md for details on getting a token.')
    quit()
print('Token found. Logging in...')
token = tokenFile.read().replace('\n', '')

for bot_module in BotModule.loaded_modules:
    if bot_module.has_background_loop:
        client.loop.create_task(bot_module.background_loop(client))

client.run(token)
<|endoftext|>